The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; |
| 2 | import { sortChecks } from "@t3tools/source-control-core/server/pullRequestChecks"; |
| 3 | import * as DateTime from "effect/DateTime"; |
| 4 | import * as Schema from "effect/Schema"; |
| 5 | import { |
| 6 | IsoDateTime, |
| 7 | NonNegativeInt, |
| 8 | PositiveInt, |
| 9 | TrimmedNonEmptyString, |
| 10 | type PullRequestActor, |
| 11 | type PullRequestCheck, |
| 12 | type PullRequestChecksState, |
| 13 | type PullRequestComment, |
| 14 | type PullRequestReaction, |
| 15 | type PullRequestReactionContent, |
| 16 | type PullRequestReviewerCandidate, |
| 17 | type PullRequestReviewThread, |
| 18 | type PullRequestViewerPermissions, |
| 19 | } from "@t3tools/contracts"; |
| 20 | import type { |
| 21 | ProviderChangeRequest, |
| 22 | ProviderChangeRequestActivity, |
| 23 | ProviderChangeRequestStack, |
| 24 | ProviderDiffSlice, |
| 25 | } from "@t3tools/source-control-core/server/PullRequestProvider"; |
| 26 | |
| 27 | const Actor = Schema.Union([ |
| 28 | Schema.Struct({ |
| 29 | kind: Schema.Literal("local"), |
| 30 | actorId: Schema.String, |
| 31 | handle: TrimmedNonEmptyString, |
| 32 | displayName: Schema.NullOr(Schema.String), |
| 33 | avatarUrl: Schema.NullOr(Schema.String), |
| 34 | bot: Schema.optional(Schema.Boolean), |
| 35 | }), |
| 36 | Schema.Struct({ |
| 37 | kind: Schema.Literal("github"), |
| 38 | actorId: Schema.String, |
| 39 | login: TrimmedNonEmptyString, |
| 40 | avatarUrl: Schema.NullOr(Schema.String), |
| 41 | accountType: Schema.optional(Schema.NullOr(Schema.String)), |
| 42 | linkedProfile: Schema.optional( |
| 43 | Schema.NullOr( |
| 44 | Schema.Struct({ handle: TrimmedNonEmptyString, actorId: Schema.optional(Schema.String) }), |
| 45 | ), |
| 46 | ), |
| 47 | }), |
| 48 | Schema.Struct({ kind: Schema.Literal("unavailable"), actorId: Schema.String }), |
| 49 | ]); |
| 50 | type Actor = typeof Actor.Type; |
| 51 | |
| 52 | const PullState = Schema.Literals(["open", "closed", "merged"]); |
| 53 | |
| 54 | export const GitCafePull = Schema.Struct({ |
| 55 | id: TrimmedNonEmptyString, |
| 56 | number: PositiveInt, |
| 57 | title: TrimmedNonEmptyString, |
| 58 | state: PullState, |
| 59 | draft: Schema.Boolean, |
| 60 | sourceBranch: Schema.String, |
| 61 | targetBranch: Schema.String, |
| 62 | headOid: Schema.NullOr(Schema.String), |
| 63 | author: Actor, |
| 64 | createdAt: IsoDateTime, |
| 65 | updatedAt: IsoDateTime, |
| 66 | version: NonNegativeInt, |
| 67 | reviewers: Schema.optional(Schema.Array(Schema.Struct({ actor: Actor }))), |
| 68 | labels: Schema.optional( |
| 69 | Schema.Array( |
| 70 | Schema.Struct({ name: TrimmedNonEmptyString, color: Schema.NullOr(Schema.String) }), |
| 71 | ), |
| 72 | ), |
| 73 | }); |
| 74 | export type GitCafePull = typeof GitCafePull.Type; |
| 75 | |
| 76 | export const GitCafePulls = Schema.Struct({ |
| 77 | items: Schema.Array(GitCafePull), |
| 78 | next: Schema.NullOr(Schema.String), |
| 79 | }); |
| 80 | |
| 81 | export const GitCafePullDetail = Schema.Struct({ |
| 82 | ...GitCafePull.fields, |
| 83 | description: Schema.NullOr(Schema.String), |
| 84 | closedAt: Schema.NullOr(IsoDateTime), |
| 85 | mergedAt: Schema.NullOr(IsoDateTime), |
| 86 | sourceRepo: Schema.NullOr(Schema.Struct({ owner: Schema.String, name: Schema.String })), |
| 87 | observedBaseOid: Schema.optional(Schema.NullOr(Schema.String)), |
| 88 | mergeRoute: Schema.optional(Schema.Literals(["native", "provider", "unsupported"])), |
| 89 | lockedAt: Schema.optional(Schema.NullOr(IsoDateTime)), |
| 90 | viewerActorId: Schema.optional(Schema.NullOr(Schema.String)), |
| 91 | mergeResultOid: Schema.optional(Schema.NullOr(Schema.String)), |
| 92 | // Set once GitHub has merged a pull request GitCafe routed there, which can be before the |
| 93 | // sync brings the merged state back. |
| 94 | providerMerge: Schema.optional( |
| 95 | Schema.NullOr( |
| 96 | Schema.Struct({ |
| 97 | mergedAt: IsoDateTime, |
| 98 | mergeCommitOid: Schema.optional(Schema.NullOr(Schema.String)), |
| 99 | }), |
| 100 | ), |
| 101 | ), |
| 102 | capabilities: Schema.Struct({ |
| 103 | comment: Schema.Boolean, |
| 104 | review: Schema.Boolean, |
| 105 | merge: Schema.Boolean, |
| 106 | edit: Schema.Boolean, |
| 107 | moderate: Schema.Boolean, |
| 108 | }), |
| 109 | }); |
| 110 | export type GitCafePullDetail = typeof GitCafePullDetail.Type; |
| 111 | |
| 112 | const CommentCapabilities = Schema.Struct({ |
| 113 | edit: Schema.Boolean, |
| 114 | hide: Schema.Boolean, |
| 115 | unhide: Schema.Boolean, |
| 116 | delete: Schema.Boolean, |
| 117 | resolve: Schema.Boolean, |
| 118 | unresolve: Schema.Boolean, |
| 119 | }); |
| 120 | |
| 121 | const GitCafeComment = Schema.Struct({ |
| 122 | id: TrimmedNonEmptyString, |
| 123 | threadId: TrimmedNonEmptyString, |
| 124 | version: Schema.optional(NonNegativeInt), |
| 125 | author: Actor, |
| 126 | body: Schema.NullOr(Schema.String), |
| 127 | createdAt: IsoDateTime, |
| 128 | path: Schema.NullOr(Schema.String), |
| 129 | // Only positive lines anchor review threads; the API allows any integer. |
| 130 | line: Schema.NullOr(Schema.Int), |
| 131 | side: Schema.NullOr(Schema.Literals(["left", "right"])), |
| 132 | commitOid: Schema.NullOr(Schema.String), |
| 133 | resolvedAt: Schema.NullOr(IsoDateTime), |
| 134 | capabilities: Schema.optional(CommentCapabilities), |
| 135 | }); |
| 136 | type GitCafeComment = typeof GitCafeComment.Type; |
| 137 | |
| 138 | export const GitCafeComments = Schema.Struct({ |
| 139 | items: Schema.Array(GitCafeComment), |
| 140 | next: Schema.NullOr(Schema.String), |
| 141 | }); |
| 142 | |
| 143 | export const GitCafeReviews = Schema.Struct({ |
| 144 | items: Schema.Array( |
| 145 | Schema.Struct({ |
| 146 | id: TrimmedNonEmptyString, |
| 147 | author: Actor, |
| 148 | body: Schema.NullOr(Schema.String), |
| 149 | verdict: Schema.Literals(["approve", "request_changes", "comment"]), |
| 150 | dismissedAt: Schema.NullOr(IsoDateTime), |
| 151 | createdAt: IsoDateTime, |
| 152 | }), |
| 153 | ), |
| 154 | next: Schema.NullOr(Schema.String), |
| 155 | }); |
| 156 | |
| 157 | export const GitCafeCommits = Schema.Struct({ |
| 158 | items: Schema.Array( |
| 159 | Schema.Struct({ oid: TrimmedNonEmptyString, summary: Schema.String, time: Schema.Finite }), |
| 160 | ), |
| 161 | truncated: Schema.Boolean, |
| 162 | next: Schema.NullOr(Schema.String), |
| 163 | headOid: Schema.String, |
| 164 | }); |
| 165 | |
| 166 | export const GitCafeLabels = Schema.Struct({ |
| 167 | items: Schema.Array( |
| 168 | Schema.Struct({ |
| 169 | id: TrimmedNonEmptyString, |
| 170 | name: TrimmedNonEmptyString, |
| 171 | color: Schema.NullOr(Schema.String), |
| 172 | description: Schema.optional(Schema.NullOr(Schema.String)), |
| 173 | }), |
| 174 | ), |
| 175 | next: Schema.NullOr(Schema.String), |
| 176 | }); |
| 177 | |
| 178 | /** A pull request's reviewers and its reviewer candidates, each actor under its id. */ |
| 179 | export const GitCafeActorEntries = Schema.Struct({ |
| 180 | items: Schema.Array(Schema.Struct({ id: TrimmedNonEmptyString, actor: Actor })), |
| 181 | next: Schema.NullOr(Schema.String), |
| 182 | }); |
| 183 | |
| 184 | export const GitCafeReactions = Schema.Struct({ |
| 185 | items: Schema.Array( |
| 186 | Schema.Struct({ |
| 187 | subject: Schema.Struct({ |
| 188 | kind: Schema.Literals(["issue", "issue_comment", "pull_request", "pull_request_comment"]), |
| 189 | id: TrimmedNonEmptyString, |
| 190 | }), |
| 191 | emoji: Schema.Union([ |
| 192 | Schema.Struct({ kind: Schema.Literal("unicode"), value: TrimmedNonEmptyString }), |
| 193 | Schema.Struct({ kind: Schema.Literal("custom"), id: TrimmedNonEmptyString }), |
| 194 | ]), |
| 195 | count: PositiveInt, |
| 196 | viewerReactionId: Schema.NullOr(Schema.String), |
| 197 | reactors: Schema.Array(Actor), |
| 198 | }), |
| 199 | ), |
| 200 | next: Schema.NullOr(Schema.String), |
| 201 | }); |
| 202 | |
| 203 | const GitCafeStack = Schema.Struct({ |
| 204 | id: TrimmedNonEmptyString, |
| 205 | number: PositiveInt, |
| 206 | revision: PositiveInt, |
| 207 | landingBase: Schema.String, |
| 208 | members: Schema.Array( |
| 209 | Schema.Struct({ |
| 210 | pullRequestNumber: PositiveInt, |
| 211 | title: Schema.String, |
| 212 | state: PullState, |
| 213 | draft: Schema.Boolean, |
| 214 | sourceBranch: Schema.String, |
| 215 | headOid: Schema.optional(Schema.String), |
| 216 | position: PositiveInt, |
| 217 | }), |
| 218 | ), |
| 219 | }); |
| 220 | export type GitCafeStack = typeof GitCafeStack.Type; |
| 221 | |
| 222 | export const GitCafeStackEnvelope = Schema.Struct({ stack: Schema.NullOr(GitCafeStack) }); |
| 223 | |
| 224 | const GitCafeDiffFile = Schema.Struct({ |
| 225 | path: TrimmedNonEmptyString, |
| 226 | oldPath: Schema.optional(Schema.NullOr(Schema.String)), |
| 227 | status: Schema.optional( |
| 228 | Schema.Literals([ |
| 229 | "added", |
| 230 | "deleted", |
| 231 | "modified", |
| 232 | "typeChanged", |
| 233 | "conflicted", |
| 234 | "renamed", |
| 235 | "copied", |
| 236 | ]), |
| 237 | ), |
| 238 | additions: Schema.optional(NonNegativeInt), |
| 239 | deletions: Schema.optional(NonNegativeInt), |
| 240 | binary: Schema.optional(Schema.Boolean), |
| 241 | tooLarge: Schema.optional(Schema.Boolean), |
| 242 | hunksOmitted: Schema.optional(Schema.Boolean), |
| 243 | isSubmodule: Schema.optional(Schema.Boolean), |
| 244 | oldOid: Schema.optional(Schema.String), |
| 245 | newOid: Schema.optional(Schema.String), |
| 246 | // `/changes` and `/compare` omit hunks; batched reads fill them. |
| 247 | hunks: Schema.optional( |
| 248 | Schema.Array( |
| 249 | Schema.Struct({ |
| 250 | oldStart: NonNegativeInt, |
| 251 | oldLines: NonNegativeInt, |
| 252 | newStart: NonNegativeInt, |
| 253 | newLines: NonNegativeInt, |
| 254 | lines: Schema.Array(Schema.Struct({ origin: Schema.String, content: Schema.String })), |
| 255 | }), |
| 256 | ), |
| 257 | ), |
| 258 | }); |
| 259 | export type GitCafeDiffFile = typeof GitCafeDiffFile.Type; |
| 260 | export const GitCafeDiffFiles = Schema.Array(GitCafeDiffFile); |
| 261 | |
| 262 | export const GitCafeDiff = Schema.Struct({ |
| 263 | items: GitCafeDiffFiles, |
| 264 | truncated: Schema.optional(Schema.Boolean), |
| 265 | }); |
| 266 | |
| 267 | export const GitCafeChecks = Schema.Struct({ |
| 268 | items: Schema.Array( |
| 269 | Schema.Struct({ |
| 270 | id: Schema.optional(Schema.NullOr(Schema.String)), |
| 271 | provider: Schema.optional(Schema.NullOr(Schema.String)), |
| 272 | githubApp: Schema.optional(Schema.NullOr(Schema.String)), |
| 273 | name: TrimmedNonEmptyString, |
| 274 | status: Schema.Literals(["queued", "in_progress", "completed"]), |
| 275 | conclusion: Schema.NullOr(Schema.String), |
| 276 | summary: Schema.NullOr(Schema.String), |
| 277 | detailsUrl: Schema.NullOr(Schema.String), |
| 278 | }), |
| 279 | ), |
| 280 | next: Schema.NullOr(Schema.String), |
| 281 | }); |
| 282 | |
| 283 | /** A user search answer and a collaborator page carry the same fields a picker shows. */ |
| 284 | export const GitCafePeople = Schema.Struct({ |
| 285 | items: Schema.Array( |
| 286 | Schema.Struct({ |
| 287 | handle: TrimmedNonEmptyString, |
| 288 | displayName: Schema.optional(Schema.NullOr(Schema.String)), |
| 289 | avatarUrl: Schema.optional(Schema.NullOr(Schema.String)), |
| 290 | }), |
| 291 | ), |
| 292 | next: Schema.NullOr(Schema.String), |
| 293 | }); |
| 294 | |
| 295 | export function toPeople( |
| 296 | people: typeof GitCafePeople.Type, |
| 297 | host: string, |
| 298 | ): ReadonlyArray<PullRequestActor> { |
| 299 | return people.items.map((person) => ({ |
| 300 | login: person.handle, |
| 301 | name: person.displayName ?? null, |
| 302 | avatarUrl: person.avatarUrl == null ? null : new URL(person.avatarUrl, `https://${host}`).href, |
| 303 | })); |
| 304 | } |
| 305 | |
| 306 | interface RepositoryOnHost { |
| 307 | readonly repository: string; |
| 308 | readonly host: string; |
| 309 | } |
| 310 | |
| 311 | function toActor(actor: Actor, host: string): PullRequestActor | null { |
| 312 | if (actor.kind === "unavailable") return null; |
| 313 | return { |
| 314 | login: actor.kind === "local" ? actor.handle : actor.login, |
| 315 | name: actor.kind === "local" ? actor.displayName : null, |
| 316 | // A mirrored GitHub account says it is a bot by its account type, not its login. |
| 317 | ...((actor.kind === "local" && actor.bot === true) || |
| 318 | (actor.kind === "github" && actor.accountType === "bot") |
| 319 | ? { isBot: true } |
| 320 | : {}), |
| 321 | // GitCafe serves its own avatars by path, so a relative one is read against the host. |
| 322 | avatarUrl: actor.avatarUrl === null ? null : new URL(actor.avatarUrl, `https://${host}`).href, |
| 323 | }; |
| 324 | } |
| 325 | |
| 326 | export function toReviewers( |
| 327 | pull: Pick<GitCafePull, "reviewers">, |
| 328 | host: string, |
| 329 | ): ReadonlyArray<PullRequestActor> { |
| 330 | return (pull.reviewers ?? []).flatMap(({ actor }) => { |
| 331 | const reviewer = toActor(actor, host); |
| 332 | return reviewer === null ? [] : [reviewer]; |
| 333 | }); |
| 334 | } |
| 335 | |
| 336 | export function toReviewerCandidates( |
| 337 | candidates: typeof GitCafeActorEntries.Type, |
| 338 | input: { |
| 339 | readonly requested: ReadonlySet<string>; |
| 340 | readonly authorActorId: string; |
| 341 | readonly host: string; |
| 342 | }, |
| 343 | ): ReadonlyArray<PullRequestReviewerCandidate> { |
| 344 | return candidates.items.flatMap(({ id, actor }) => { |
| 345 | const reviewer = id === input.authorActorId ? null : toActor(actor, input.host); |
| 346 | return reviewer === null |
| 347 | ? [] |
| 348 | : [{ ...reviewer, id, kind: "user" as const, isRequested: input.requested.has(id) }]; |
| 349 | }); |
| 350 | } |
| 351 | |
| 352 | function reviewerLogins(actor: Actor, host: string): ReadonlyArray<string> { |
| 353 | const reviewer = toActor(actor, host); |
| 354 | if (reviewer === null) return []; |
| 355 | return actor.kind === "github" && actor.linkedProfile |
| 356 | ? [reviewer.login, actor.linkedProfile.handle] |
| 357 | : [reviewer.login]; |
| 358 | } |
| 359 | |
| 360 | export function toChangeRequest( |
| 361 | pull: GitCafePull, |
| 362 | target: RepositoryOnHost, |
| 363 | ): ProviderChangeRequest { |
| 364 | return { |
| 365 | number: pull.number, |
| 366 | title: pull.title, |
| 367 | url: `https://${target.host}/${target.repository}/pulls/${pull.number}`, |
| 368 | author: toActor(pull.author, target.host), |
| 369 | headBranch: pull.sourceBranch, |
| 370 | baseBranch: pull.targetBranch, |
| 371 | state: pull.state, |
| 372 | isDraft: pull.draft, |
| 373 | mergeability: "unknown", |
| 374 | additions: 0, |
| 375 | deletions: 0, |
| 376 | createdAt: pull.createdAt, |
| 377 | updatedAt: pull.updatedAt, |
| 378 | reviewRequestLogins: (pull.reviewers ?? []).flatMap(({ actor }) => |
| 379 | reviewerLogins(actor, target.host), |
| 380 | ), |
| 381 | labels: (pull.labels ?? []).map(({ name, color }) => ({ name, color })), |
| 382 | }; |
| 383 | } |
| 384 | |
| 385 | function isViewerAuthor(detail: GitCafePullDetail): boolean { |
| 386 | const viewer = detail.viewerActorId; |
| 387 | if (viewer == null) return false; |
| 388 | const { author } = detail; |
| 389 | return ( |
| 390 | author.actorId === viewer || |
| 391 | (author.kind === "github" && author.linkedProfile?.actorId === viewer) |
| 392 | ); |
| 393 | } |
| 394 | |
| 395 | export function toViewerPermissions(detail: GitCafePullDetail): PullRequestViewerPermissions { |
| 396 | const { comment, edit, review, merge, moderate } = detail.capabilities; |
| 397 | const open = comment && (detail.lockedAt == null || moderate); |
| 398 | return { |
| 399 | actions: [ |
| 400 | ...(edit && detail.state === "open" |
| 401 | ? ([detail.draft ? "ready" : "draft", "close"] as const) |
| 402 | : edit && detail.state === "closed" |
| 403 | ? (["reopen"] as const) |
| 404 | : []), |
| 405 | ...(merge && detail.state === "open" && !detail.draft ? (["merge"] as const) : []), |
| 406 | ], |
| 407 | stackRebase: merge, |
| 408 | comment: open, |
| 409 | resolve: open, |
| 410 | // GitCafe refuses an author's approval and request for changes, as GitHub does. |
| 411 | verdicts: !review |
| 412 | ? [] |
| 413 | : isViewerAuthor(detail) |
| 414 | ? ["comment"] |
| 415 | : ["approve", "request-changes", "comment"], |
| 416 | requestReviewers: edit && detail.state === "open", |
| 417 | labels: edit && detail.state === "open", |
| 418 | editChangeRequest: edit, |
| 419 | // GitCafe's only branch update moves a whole stack. |
| 420 | updateMethods: [], |
| 421 | }; |
| 422 | } |
| 423 | |
| 424 | const REACTIONS: Readonly<Record<string, PullRequestReactionContent>> = { |
| 425 | "👍": "thumbs-up", |
| 426 | "👎": "thumbs-down", |
| 427 | "😄": "laugh", |
| 428 | "🎉": "hooray", |
| 429 | "😕": "confused", |
| 430 | "❤": "heart", |
| 431 | "🚀": "rocket", |
| 432 | "👀": "eyes", |
| 433 | }; |
| 434 | |
| 435 | export const REACTION_EMOJI: Readonly<Record<PullRequestReactionContent, string>> = { |
| 436 | "thumbs-up": "👍", |
| 437 | "thumbs-down": "👎", |
| 438 | laugh: "😄", |
| 439 | hooray: "🎉", |
| 440 | confused: "😕", |
| 441 | heart: "❤️", |
| 442 | rocket: "🚀", |
| 443 | eyes: "👀", |
| 444 | }; |
| 445 | |
| 446 | export function reactionContent(emoji: string): PullRequestReactionContent | undefined { |
| 447 | return REACTIONS[emoji.replaceAll("\uFE0F", "")]; |
| 448 | } |
| 449 | |
| 450 | function toReactions(data: typeof GitCafeReactions.Type, host: string) { |
| 451 | const reactions: Array<PullRequestReaction> = []; |
| 452 | const byComment = new Map<string, Array<PullRequestReaction>>(); |
| 453 | for (const item of data.items) { |
| 454 | const content = item.emoji.kind === "unicode" ? reactionContent(item.emoji.value) : undefined; |
| 455 | if (content === undefined) continue; |
| 456 | const reaction: PullRequestReaction = { |
| 457 | content, |
| 458 | count: item.count, |
| 459 | actors: item.reactors.flatMap((actor) => { |
| 460 | const reactor = toActor(actor, host); |
| 461 | return reactor === null ? [] : [reactor.login]; |
| 462 | }), |
| 463 | viewerHasReacted: item.viewerReactionId !== null, |
| 464 | }; |
| 465 | if (item.subject.kind === "pull_request") reactions.push(reaction); |
| 466 | else if (item.subject.kind === "pull_request_comment") |
| 467 | byComment.set(item.subject.id, [...(byComment.get(item.subject.id) ?? []), reaction]); |
| 468 | } |
| 469 | return { reactions, byComment }; |
| 470 | } |
| 471 | |
| 472 | const REVIEW_STATES = { |
| 473 | approve: "approved", |
| 474 | request_changes: "changes_requested", |
| 475 | comment: "commented", |
| 476 | } as const; |
| 477 | |
| 478 | export function toActivity(input: { |
| 479 | readonly comments: typeof GitCafeComments.Type; |
| 480 | readonly reviews: typeof GitCafeReviews.Type; |
| 481 | readonly commits: typeof GitCafeCommits.Type; |
| 482 | readonly reactions?: typeof GitCafeReactions.Type; |
| 483 | readonly headOid?: string; |
| 484 | readonly host: string; |
| 485 | }): ProviderChangeRequestActivity { |
| 486 | const { host } = input; |
| 487 | const reactions = input.reactions === undefined ? undefined : toReactions(input.reactions, host); |
| 488 | const remark = (comment: GitCafeComment) => ({ |
| 489 | id: comment.id, |
| 490 | author: toActor(comment.author, host), |
| 491 | body: comment.body ?? "", |
| 492 | createdAt: comment.createdAt, |
| 493 | url: null, |
| 494 | ...(comment.capabilities === undefined ? {} : { canEdit: comment.capabilities.edit }), |
| 495 | ...(reactions === undefined ? {} : { reactions: reactions.byComment.get(comment.id) ?? [] }), |
| 496 | }); |
| 497 | const ordered = input.comments.items.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt)); |
| 498 | const groups = new Map<string, Array<GitCafeComment>>(); |
| 499 | for (const comment of ordered) { |
| 500 | if (!comment.path || comment.line === null || comment.line < 1 || comment.side === null) |
| 501 | continue; |
| 502 | groups.set(comment.threadId, [...(groups.get(comment.threadId) ?? []), comment]); |
| 503 | } |
| 504 | const reviewThreads = [...groups.values()].map((group): PullRequestReviewThread => { |
| 505 | const first = group[0]!; |
| 506 | const latest = group.at(-1)!; |
| 507 | const root = group.find((comment) => comment.id === comment.threadId); |
| 508 | return { |
| 509 | id: first.threadId, |
| 510 | path: first.path!, |
| 511 | line: first.line, |
| 512 | side: first.side!, |
| 513 | isResolved: root?.resolvedAt != null, |
| 514 | isOutdated: |
| 515 | input.headOid !== undefined && |
| 516 | latest.commitOid !== null && |
| 517 | latest.commitOid !== input.headOid, |
| 518 | comments: group.map(remark), |
| 519 | ...(root?.capabilities === undefined |
| 520 | ? {} |
| 521 | : { |
| 522 | canResolve: |
| 523 | root.resolvedAt === null ? root.capabilities.resolve : root.capabilities.unresolve, |
| 524 | }), |
| 525 | }; |
| 526 | }); |
| 527 | const comments: Array<PullRequestComment> = [ |
| 528 | ...ordered.map((comment) => ({ |
| 529 | ...remark(comment), |
| 530 | kind: comment.path === null ? ("issue-comment" as const) : ("review-comment" as const), |
| 531 | path: comment.path, |
| 532 | reviewState: null, |
| 533 | })), |
| 534 | ...input.reviews.items.map((review) => ({ |
| 535 | id: review.id, |
| 536 | kind: "review" as const, |
| 537 | author: toActor(review.author, host), |
| 538 | body: review.body ?? "", |
| 539 | createdAt: review.createdAt, |
| 540 | url: null, |
| 541 | path: null, |
| 542 | reviewState: review.dismissedAt !== null ? "dismissed" : REVIEW_STATES[review.verdict], |
| 543 | })), |
| 544 | ]; |
| 545 | return { |
| 546 | comments: comments.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt)), |
| 547 | commentCount: input.comments.items.length + input.reviews.items.length, |
| 548 | commentsTruncated: input.comments.next !== null || input.reviews.next !== null, |
| 549 | reviewThreads, |
| 550 | commits: input.commits.items.map((commit) => ({ |
| 551 | oid: commit.oid, |
| 552 | messageHeadline: commit.summary, |
| 553 | committedDate: DateTime.formatIso(DateTime.makeUnsafe(commit.time * 1_000)), |
| 554 | })), |
| 555 | ...(reactions === undefined ? {} : { reactions: reactions.reactions }), |
| 556 | }; |
| 557 | } |
| 558 | |
| 559 | export function toStack(stack: GitCafeStack, target: RepositoryOnHost): ProviderChangeRequestStack { |
| 560 | return { |
| 561 | id: stack.id, |
| 562 | number: stack.number, |
| 563 | url: `https://${target.host}/${target.repository}/stacks/${stack.number}`, |
| 564 | base: stack.landingBase, |
| 565 | layers: stack.members |
| 566 | .toSorted((a, b) => a.position - b.position) |
| 567 | .map((member) => ({ |
| 568 | number: member.pullRequestNumber, |
| 569 | title: member.title, |
| 570 | headBranch: member.sourceBranch, |
| 571 | state: member.state, |
| 572 | isDraft: member.draft, |
| 573 | ...(member.headOid === undefined ? {} : { headSha: member.headOid }), |
| 574 | })), |
| 575 | }; |
| 576 | } |
| 577 | |
| 578 | function isEOFMarker(origin: string | undefined) { |
| 579 | return origin === "=" || origin === ">" || origin === "<"; |
| 580 | } |
| 581 | |
| 582 | export function toDiff(diff: typeof GitCafeDiff.Type): ProviderDiffSlice { |
| 583 | const chunks: Array<string> = []; |
| 584 | const omittedFileStats: Array<{ path: string; additions: number; deletions: number }> = []; |
| 585 | for (const file of diff.items) { |
| 586 | const oldPath = file.oldPath ?? file.path; |
| 587 | const a = quoteGitPatchPath(`a/${oldPath}`); |
| 588 | const b = quoteGitPatchPath(`b/${file.path}`); |
| 589 | const before = file.status === "added" ? "/dev/null" : a; |
| 590 | const after = file.status === "deleted" ? "/dev/null" : b; |
| 591 | const mode = file.isSubmodule ? "160000" : "100644"; |
| 592 | const lines = [`diff --git ${a} ${b}`]; |
| 593 | if (file.status === "added") lines.push(`new file mode ${mode}`); |
| 594 | if (file.status === "deleted") lines.push(`deleted file mode ${mode}`); |
| 595 | if (file.status === "renamed" || file.status === "copied") { |
| 596 | const action = file.status === "renamed" ? "rename" : "copy"; |
| 597 | const hasChanges = |
| 598 | (file.hunks?.length ?? 0) > 0 || |
| 599 | (file.additions ?? 0) > 0 || |
| 600 | (file.deletions ?? 0) > 0 || |
| 601 | file.binary || |
| 602 | file.tooLarge || |
| 603 | file.hunksOmitted; |
| 604 | // GitCafe has no similarity score; Pierre needs this header to retain rename metadata. |
| 605 | lines.push( |
| 606 | `similarity index ${hasChanges ? 0 : 100}%`, |
| 607 | `${action} from ${quoteGitPatchPath(oldPath)}`, |
| 608 | `${action} to ${quoteGitPatchPath(file.path)}`, |
| 609 | ); |
| 610 | } |
| 611 | if (file.binary) { |
| 612 | lines.push(`Binary files ${before} and ${after} differ`); |
| 613 | } else if (file.tooLarge || file.hunksOmitted) { |
| 614 | omittedFileStats.push({ |
| 615 | path: file.path, |
| 616 | additions: file.additions ?? 0, |
| 617 | deletions: file.deletions ?? 0, |
| 618 | }); |
| 619 | } else if (file.isSubmodule) { |
| 620 | const hasOld = file.status !== "added" && file.oldOid !== undefined; |
| 621 | const hasNew = file.status !== "deleted" && file.newOid !== undefined; |
| 622 | lines.push(`--- ${before}`, `+++ ${after}`); |
| 623 | lines.push(`@@ -${hasOld ? "1" : "0,0"} +${hasNew ? "1" : "0,0"} @@`); |
| 624 | if (hasOld) lines.push(`-Subproject commit ${file.oldOid}`); |
| 625 | if (hasNew) lines.push(`+Subproject commit ${file.newOid}`); |
| 626 | } else { |
| 627 | const hunks = file.hunks ?? []; |
| 628 | if (hunks.length > 0) lines.push(`--- ${before}`, `+++ ${after}`); |
| 629 | for (const hunk of hunks) { |
| 630 | lines.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`); |
| 631 | for (const [index, line] of hunk.lines.entries()) { |
| 632 | if (isEOFMarker(line.origin)) { |
| 633 | lines.push("\\ No newline at end of file"); |
| 634 | } else { |
| 635 | lines.push(`${line.origin}${line.content.replace(/\n$/u, "")}`); |
| 636 | if ( |
| 637 | ["+", "-", " "].includes(line.origin) && |
| 638 | !line.content.endsWith("\n") && |
| 639 | !isEOFMarker(hunk.lines[index + 1]?.origin) |
| 640 | ) { |
| 641 | lines.push("\\ No newline at end of file"); |
| 642 | } |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | chunks.push(lines.join("\n")); |
| 648 | } |
| 649 | return { |
| 650 | patch: chunks.length === 0 ? "" : `${chunks.join("\n")}\n`, |
| 651 | truncated: diff.truncated === true || omittedFileStats.length > 0, |
| 652 | nextCursor: null, |
| 653 | ...(omittedFileStats.length === 0 ? {} : { omittedFileStats }), |
| 654 | }; |
| 655 | } |
| 656 | |
| 657 | function checkStatus(check: (typeof GitCafeChecks.Type.items)[number]): PullRequestCheck["status"] { |
| 658 | if (check.status !== "completed") return "pending"; |
| 659 | switch (check.conclusion) { |
| 660 | case "success": |
| 661 | return "success"; |
| 662 | case "neutral": |
| 663 | return "neutral"; |
| 664 | case "skipped": |
| 665 | return "skipped"; |
| 666 | case "cancelled": |
| 667 | return "cancelled"; |
| 668 | case "action_required": |
| 669 | return "action-required"; |
| 670 | default: |
| 671 | return "failure"; |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | type GitCafeCheck = (typeof GitCafeChecks.Type.items)[number]; |
| 676 | |
| 677 | /** A check run's id, which grows with each run. Commit statuses (`status:…`) carry no such order. */ |
| 678 | function runOrder(check: GitCafeCheck): bigint | null { |
| 679 | return check.id != null && /^\d+$/u.test(check.id) ? BigInt(check.id) : null; |
| 680 | } |
| 681 | |
| 682 | /** |
| 683 | * GitCafe lists every run of a commit's checks, so a re-run arrives beside the run it replaced. |
| 684 | * The newest run is the check's state; an older failure is history, not a failing check. Runs whose |
| 685 | * order cannot be told apart are all kept, so no failure is hidden. Two reporters may share a check |
| 686 | * name, so a run only replaces runs from the same provider and GitHub app. |
| 687 | */ |
| 688 | export function toChecks(checks: typeof GitCafeChecks.Type): ReadonlyArray<PullRequestCheck> { |
| 689 | const kept: Array<GitCafeCheck> = []; |
| 690 | const newestByKey = new Map<string, { index: number; order: bigint }>(); |
| 691 | for (const check of checks.items) { |
| 692 | const order = runOrder(check); |
| 693 | if (order === null) { |
| 694 | kept.push(check); |
| 695 | continue; |
| 696 | } |
| 697 | const key = JSON.stringify([check.provider ?? null, check.githubApp ?? null, check.name]); |
| 698 | const newest = newestByKey.get(key); |
| 699 | if (newest === undefined) { |
| 700 | newestByKey.set(key, { index: kept.length, order }); |
| 701 | kept.push(check); |
| 702 | } else if (order > newest.order) { |
| 703 | kept[newest.index] = check; |
| 704 | newest.order = order; |
| 705 | } |
| 706 | } |
| 707 | return sortChecks( |
| 708 | kept.map((check) => ({ |
| 709 | name: check.name, |
| 710 | status: checkStatus(check), |
| 711 | description: check.summary, |
| 712 | url: check.detailsUrl, |
| 713 | })), |
| 714 | ); |
| 715 | } |
| 716 | |
| 717 | export function checksStateOf( |
| 718 | checks: ReadonlyArray<PullRequestCheck>, |
| 719 | ): PullRequestChecksState | null { |
| 720 | const statuses = new Set(checks.map((check) => check.status)); |
| 721 | if (statuses.has("failure") || statuses.has("cancelled")) return "failing"; |
| 722 | if (statuses.has("pending") || statuses.has("action-required")) return "pending"; |
| 723 | return statuses.has("success") ? "passing" : null; |
| 724 | } |