diff-model.ts
This file
Path
apps/web/src/features/code/diff-model.ts
349 lines · 9.2 KiB · TypeScript
Last changed by
Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72
History of this fileTake it
Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
line 1why, one step back1/**Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72
lines 2–4why, one step back2 * Parsed by the same parser the drawing uses, so the server's plain-text diff3 * and the browser's highlighted one hold the same hunks, line for line. No4 * React and no DOM: both renders read it.Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 5–349why, one step back5 */6import { parseDiffFromFile } from "@pierre/diffs";7import type { FileDiffMetadata } from "@pierre/diffs";8import type { ChangedFile } from "@repo/protocol/domain/code";9import { Option } from "effect";1011export const LONG_FILE = 80;1213export const fileDiffOf = (14 file: ChangedFile15): Option.Option<FileDiffMetadata> => {16 if (17 file.binary ||18 (file.oldText === undefined && file.newText === undefined)19 ) {20 return Option.none();21 }2223 const before =24 file.status === "added" || file.oldText === undefined25 ? null26 : { contents: file.oldText, name: file.path };2728 const after =29 file.status === "deleted" || file.newText === undefined30 ? null31 : { contents: file.newText, name: file.path };3233 const diff = parseDiffFromFile(before, after);3435 // Keyed by both blobs, so a file drawn once is never highlighted again.36 diff.cacheKey = `diff:${file.before ?? "none"}:${file.after ?? "none"}`;3738 return Option.some(diff);39};4041const CHANGE_TYPES = {42 added: "new",43 deleted: "deleted",44 modified: "change",45} as const satisfies Record<ChangedFile["status"], FileDiffMetadata["type"]>;4647export const emptyDiffOf = (file: ChangedFile): FileDiffMetadata => ({48 additionLines: [],49 cacheKey: `diff:${file.before ?? "none"}:${file.after ?? "none"}`,50 deletionLines: [],51 hunks: [],52 isPartial: false,53 name: file.path,54 splitLineCount: 0,55 type: CHANGE_TYPES[file.status],56 unifiedLineCount: 0,57});5859export interface Counts {60 readonly additions: number;61 readonly deletions: number;62}6364const NONE: Counts = { additions: 0, deletions: 0 };6566export const countsOf = (diff: Option.Option<FileDiffMetadata>): Counts => {67 if (Option.isNone(diff)) {68 return NONE;69 }7071 let additions = 0;72 let deletions = 0;7374 for (const hunk of diff.value.hunks) {75 additions += hunk.additionLines;76 deletions += hunk.deletionLines;77 }7879 return { additions, deletions };80};8182export interface DrawnFile {83 readonly file: ChangedFile;84 readonly diff: Option.Option<FileDiffMetadata>;85 readonly counts: Counts;86 readonly folded: boolean;87}8889export const treeOrder = (left: string, right: string) => {90 const a = left.split("/");91 const b = right.split("/");9293 for (let index = 0; index < Math.min(a.length, b.length); index += 1) {94 const x = a[index] ?? "";95 const y = b[index] ?? "";9697 if (x !== y) {98 const xFolder = index < a.length - 1;99 const yFolder = index < b.length - 1;100101 if (xFolder !== yFolder) {102 return xFolder ? -1 : 1;103 }104105 return x.localeCompare(y, "en");106 }107 }108109 return a.length - b.length;110};111112export const drawnFiles = (113 files: readonly ChangedFile[]114): readonly DrawnFile[] =>115 files116 .toSorted((a, b) => treeOrder(a.path, b.path))117 .map((file) => {118 const diff = fileDiffOf(file);119 const counts = countsOf(diff);120121 return {122 counts,123 diff,124 file,125 folded:126 file.status !== "modified" &&127 counts.additions + counts.deletions > LONG_FILE,128 };129 });130131export const isTestPath = (path: string) =>132 /(?:^|\/)(?:tests?|__tests__|spec)\//u.test(path) ||133 /\.(?:test|spec)\.[^/]+$/u.test(path);134135export const globTest = (glob: string): ((path: string) => boolean) => {136 const pattern = glob137 .replaceAll(/[.+^${}()|[\]\\]/gu, "\\$&")138 .replaceAll("**/", "\u0000")139 .replaceAll("**", "\u0001")140 .replaceAll("*", "[^/]*")141 .replaceAll("?", "[^/]")142 .replaceAll("\u0000", "(?:.*/)?")143 .replaceAll("\u0001", ".*");144145 const whole = new RegExp(`^${pattern}(?:/.*)?$`, "u");146147 return (path) => whole.test(path);148};149150export interface StatsPart extends Counts {151 readonly label: "other" | "territory" | "tests";152 readonly files: number;153}154155export interface DiffStats extends Counts {156 readonly files: number;157 readonly parts: readonly StatsPart[];158}159160export const statsOf = (161 files: readonly DrawnFile[],162 territory: readonly string[] = []163): DiffStats => {164 const inTerritory = territory.map(globTest);165166 const labelOf = (path: string): StatsPart["label"] => {167 if (isTestPath(path)) {168 return "tests";169 }170171 return inTerritory.some((test) => test(path)) ? "territory" : "other";172 };173174 const parts = (["territory", "tests", "other"] as const).flatMap(175 (label): readonly StatsPart[] => {176 const mine = files.filter(({ file }) => labelOf(file.path) === label);177178 return mine.length === 0179 ? []180 : [181 {182 additions: mine.reduce(183 (sum, { counts }) => sum + counts.additions,184 0185 ),186 deletions: mine.reduce(187 (sum, { counts }) => sum + counts.deletions,188 0189 ),190 files: mine.length,191 label,192 },193 ];194 }195 );196197 return {198 additions: parts.reduce((sum, part) => sum + part.additions, 0),199 deletions: parts.reduce((sum, part) => sum + part.deletions, 0),200 files: files.length,201 parts,202 };203};204205export type PlainRow =206 | { readonly kind: "separator"; readonly lines: number }207 | {208 readonly kind: "context" | "addition" | "deletion";209 readonly number: number;210 readonly text: string;211 };212213const bare = (line: string | undefined) => (line ?? "").replace(/\r?\n$/u, "");214215export const unifiedRows = (diff: FileDiffMetadata): readonly PlainRow[] => {216 const rows: PlainRow[] = [];217 let lastAddition = 0;218219 for (const hunk of diff.hunks) {220 if (hunk.collapsedBefore > 0) {221 rows.push({ kind: "separator", lines: hunk.collapsedBefore });222 }223224 for (const content of hunk.hunkContent) {225 if (content.type === "context") {226 for (let line = 0; line < content.lines; line += 1) {227 const index = content.additionLineIndex + line;228229 rows.push({230 kind: "context",231 number: index + 1,232 text: bare(diff.additionLines[index]),233 });234 }235 } else {236 for (let line = 0; line < content.deletions; line += 1) {237 const index = content.deletionLineIndex + line;238239 rows.push({240 kind: "deletion",241 number: index + 1,242 text: bare(diff.deletionLines[index]),243 });244 }245246 for (let line = 0; line < content.additions; line += 1) {247 const index = content.additionLineIndex + line;248249 rows.push({250 kind: "addition",251 number: index + 1,252 text: bare(diff.additionLines[index]),253 });254 }255 }256 }257258 lastAddition = hunk.additionStart - 1 + hunk.additionCount;259 }260261 const after = diff.isPartial ? 0 : diff.additionLines.length - lastAddition;262263 if (diff.hunks.length > 0 && after > 0 && diff.type !== "deleted") {264 rows.push({ kind: "separator", lines: after });265 }266267 return rows;268};269270type Line = Extract<PlainRow, { readonly number: number }>;271272export type SplitRow =273 | { readonly kind: "separator"; readonly lines: number }274 | {275 readonly kind: "pair";276 readonly left?: Line;277 readonly right?: Line;278 };279280export const splitRows = (diff: FileDiffMetadata): readonly SplitRow[] => {281 const rows: SplitRow[] = [];282 let lastAddition = 0;283284 for (const hunk of diff.hunks) {285 if (hunk.collapsedBefore > 0) {286 rows.push({ kind: "separator", lines: hunk.collapsedBefore });287 }288289 for (const content of hunk.hunkContent) {290 if (content.type === "context") {291 for (let line = 0; line < content.lines; line += 1) {292 const old = content.deletionLineIndex + line;293 const index = content.additionLineIndex + line;294295 rows.push({296 kind: "pair",297 left: {298 kind: "context",299 number: old + 1,300 text: bare(diff.deletionLines[old]),301 },302 right: {303 kind: "context",304 number: index + 1,305 text: bare(diff.additionLines[index]),306 },307 });308 }309 } else {310 const span = Math.max(content.deletions, content.additions);311312 for (let line = 0; line < span; line += 1) {313 const old = content.deletionLineIndex + line;314 const index = content.additionLineIndex + line;315316 const left: Line = {317 kind: "deletion",318 number: old + 1,319 text: bare(diff.deletionLines[old]),320 };321322 const right: Line = {323 kind: "addition",324 number: index + 1,325 text: bare(diff.additionLines[index]),326 };327328 if (line < content.deletions && line < content.additions) {329 rows.push({ kind: "pair", left, right });330 } else if (line < content.deletions) {331 rows.push({ kind: "pair", left });332 } else {333 rows.push({ kind: "pair", right });334 }335 }336 }337 }338339 lastAddition = hunk.additionStart - 1 + hunk.additionCount;340 }341342 const after = diff.isPartial ? 0 : diff.additionLines.length - lastAddition;343344 if (diff.hunks.length > 0 && after > 0 && diff.type !== "deleted") {345 rows.push({ kind: "separator", lines: after });346 }347348 return rows;349};