Skip to content
Myr

diff-model.ts

This file

Path

apps/web/src/features/code/diff-model.ts

396 lines · 11.5 KiB · TypeScript

Last changed by

Merge build/1211-code-browseroscabrielbefore adoptiona6808d3

History of this file

Take it

Merge build/1211-code-browseroscabrielbefore adoptiona6808d3

lines 1–396why, one step back
1/**
2 * A commit's changed files as the diff draws them, worked out once by the3 * same parser the drawing uses (`@pierre/diffs`' `parseDiffFromFile`), so4 * the server's plain-text diff and the highlighted one the browser draws5 * over it hold the same hunks, line for line: the swap moves nothing.6 *7 * Also here: each file's `+n −m`, which files start folded (an added or8 * deleted file past `LONG_FILE` lines), the order a tree lists paths in,9 * and a commit's stats split by path (the ask's territory, its tests, the10 * rest), counted by rule, never by a model.11 *12 * No React and no DOM: the server's render and the browser's both read it.13 */14import { parseDiffFromFile } from "@pierre/diffs";15import type { FileDiffMetadata } from "@pierre/diffs";16import type { ChangedFile } from "@repo/protocol/domain/code";17import { Option } from "effect";1819/** Past this many lines an added or deleted file starts folded. */20export const LONG_FILE = 80;2122/** A file's diff, parsed from both its texts; none for a binary or unsent file. */23export const fileDiffOf = (24 file: ChangedFile25): Option.Option<FileDiffMetadata> => {26 if (27 file.binary ||28 (file.oldText === undefined && file.newText === undefined)29 ) {30 return Option.none();31 }3233 const before =34 file.status === "added" || file.oldText === undefined35 ? null36 : { contents: file.oldText, name: file.path };3738 const after =39 file.status === "deleted" || file.newText === undefined40 ? null41 : { contents: file.newText, name: file.path };4243 const diff = parseDiffFromFile(before, after);4445 // Keyed by both blobs, so a file drawn once is never highlighted again.46 diff.cacheKey = `diff:${file.before ?? "none"}:${file.after ?? "none"}`;4748 return Option.some(diff);49};5051/** Each kind of change as the drawing names it. */52const CHANGE_TYPES = {53 added: "new",54 deleted: "deleted",55 modified: "change",56} as const satisfies Record<ChangedFile["status"], FileDiffMetadata["type"]>;5758/** A diff with no lines: a header alone, for a file whose lines are not shown. */59export const emptyDiffOf = (file: ChangedFile): FileDiffMetadata => ({60 additionLines: [],61 cacheKey: `diff:${file.before ?? "none"}:${file.after ?? "none"}`,62 deletionLines: [],63 hunks: [],64 isPartial: false,65 name: file.path,66 splitLineCount: 0,67 type: CHANGE_TYPES[file.status],68 unifiedLineCount: 0,69});7071/** Lines a file's diff adds and removes. */72export interface Counts {73 readonly additions: number;74 readonly deletions: number;75}7677const NONE: Counts = { additions: 0, deletions: 0 };7879/** What `diff` adds and removes, line by line. */80export const countsOf = (diff: Option.Option<FileDiffMetadata>): Counts => {81 if (Option.isNone(diff)) {82 return NONE;83 }8485 let additions = 0;86 let deletions = 0;8788 for (const hunk of diff.value.hunks) {89 additions += hunk.additionLines;90 deletions += hunk.deletionLines;91 }9293 return { additions, deletions };94};9596/** A changed file with its parsed diff and counts. */97export interface DrawnFile {98 readonly file: ChangedFile;99 readonly diff: Option.Option<FileDiffMetadata>;100 readonly counts: Counts;101 /** Whether it starts folded: added or deleted, past `LONG_FILE` lines. */102 readonly folded: boolean;103}104105/**106 * The order a file tree lists paths in: segment by segment, a folder107 * before a file at the same level, then by name.108 */109export const treeOrder = (left: string, right: string) => {110 const a = left.split("/");111 const b = right.split("/");112113 for (let index = 0; index < Math.min(a.length, b.length); index += 1) {114 const x = a[index] ?? "";115 const y = b[index] ?? "";116117 if (x !== y) {118 const xFolder = index < a.length - 1;119 const yFolder = index < b.length - 1;120121 if (xFolder !== yFolder) {122 return xFolder ? -1 : 1;123 }124125 return x.localeCompare(y, "en");126 }127 }128129 return a.length - b.length;130};131132/** `files` in tree order, each parsed and counted. */133export const drawnFiles = (134 files: readonly ChangedFile[]135): readonly DrawnFile[] =>136 files137 .toSorted((a, b) => treeOrder(a.path, b.path))138 .map((file) => {139 const diff = fileDiffOf(file);140 const counts = countsOf(diff);141142 return {143 counts,144 diff,145 file,146 folded:147 file.status !== "modified" &&148 counts.additions + counts.deletions > LONG_FILE,149 };150 });151152/** A test file, by its path: a test folder, or a `.test.` or `.spec.` name. */153export const isTestPath = (path: string) =>154 /(?:^|\/)(?:tests?|__tests__|spec)\//u.test(path) ||155 /\.(?:test|spec)\.[^/]+$/u.test(path);156157/** A territory glob (`src/format/**`, `src/*.ts`) as a test on a path. */158export const globTest = (glob: string): ((path: string) => boolean) => {159 const pattern = glob160 .replaceAll(/[.+^${}()|[\]\\]/gu, "\\$&")161 .replaceAll("**/", "\u0000")162 .replaceAll("**", "\u0001")163 .replaceAll("*", "[^/]*")164 .replaceAll("?", "[^/]")165 .replaceAll("\u0000", "(?:.*/)?")166 .replaceAll("\u0001", ".*");167168 // A folder named without a pattern covers what is inside it.169 const whole = new RegExp(`^${pattern}(?:/.*)?$`, "u");170171 return (path) => whole.test(path);172};173174/** One part of a commit's stats: what its paths add and remove. */175export interface StatsPart extends Counts {176 readonly label: "other" | "territory" | "tests";177 readonly files: number;178}179180/** A commit's stats: files, lines added and removed, and the parts by path. */181export interface DiffStats extends Counts {182 readonly files: number;183 readonly parts: readonly StatsPart[];184}185186/**187 * The stats of `files`. With the ask's territory, a path it covers is the188 * territory's, a test file the tests', anything else the rest; without189 * one, a test file is the tests' and the rest is the rest. Empty parts are190 * left out.191 */192export const statsOf = (193 files: readonly DrawnFile[],194 territory: readonly string[] = []195): DiffStats => {196 const inTerritory = territory.map(globTest);197198 const labelOf = (path: string): StatsPart["label"] => {199 if (isTestPath(path)) {200 return "tests";201 }202203 return inTerritory.some((test) => test(path)) ? "territory" : "other";204 };205206 const parts = (["territory", "tests", "other"] as const).flatMap(207 (label): readonly StatsPart[] => {208 const mine = files.filter(({ file }) => labelOf(file.path) === label);209210 return mine.length === 0211 ? []212 : [213 {214 additions: mine.reduce(215 (sum, { counts }) => sum + counts.additions,216 0217 ),218 deletions: mine.reduce(219 (sum, { counts }) => sum + counts.deletions,220 0221 ),222 files: mine.length,223 label,224 },225 ];226 }227 );228229 return {230 additions: parts.reduce((sum, part) => sum + part.additions, 0),231 deletions: parts.reduce((sum, part) => sum + part.deletions, 0),232 files: files.length,233 parts,234 };235};236237/** One row of a plain diff, as unified or split draws it. */238export type PlainRow =239 | { readonly kind: "separator"; readonly lines: number }240 | {241 readonly kind: "context" | "addition" | "deletion";242 readonly number: number;243 readonly text: string;244 };245246/** A line as the diff stores it, without its line ending. */247const bare = (line: string | undefined) => (line ?? "").replace(/\r?\n$/u, "");248249/**250 * `diff` as unified rows: before each hunk the unchanged lines it skips251 * as one separator, then its lines (deletions before additions in a252 * change, each numbered on its own side), and after the last hunk the253 * unchanged lines left.254 */255export const unifiedRows = (diff: FileDiffMetadata): readonly PlainRow[] => {256 const rows: PlainRow[] = [];257 let lastAddition = 0;258259 for (const hunk of diff.hunks) {260 if (hunk.collapsedBefore > 0) {261 rows.push({ kind: "separator", lines: hunk.collapsedBefore });262 }263264 for (const content of hunk.hunkContent) {265 if (content.type === "context") {266 for (let line = 0; line < content.lines; line += 1) {267 const index = content.additionLineIndex + line;268269 rows.push({270 kind: "context",271 number: index + 1,272 text: bare(diff.additionLines[index]),273 });274 }275 } else {276 for (let line = 0; line < content.deletions; line += 1) {277 const index = content.deletionLineIndex + line;278279 rows.push({280 kind: "deletion",281 number: index + 1,282 text: bare(diff.deletionLines[index]),283 });284 }285286 for (let line = 0; line < content.additions; line += 1) {287 const index = content.additionLineIndex + line;288289 rows.push({290 kind: "addition",291 number: index + 1,292 text: bare(diff.additionLines[index]),293 });294 }295 }296 }297298 lastAddition = hunk.additionStart - 1 + hunk.additionCount;299 }300301 const after = diff.isPartial ? 0 : diff.additionLines.length - lastAddition;302303 if (diff.hunks.length > 0 && after > 0 && diff.type !== "deleted") {304 rows.push({ kind: "separator", lines: after });305 }306307 return rows;308};309310/** One numbered line of a plain diff. */311type Line = Extract<PlainRow, { readonly number: number }>;312313/** One row of a split diff: the old side and the new, either empty. */314export type SplitRow =315 | { readonly kind: "separator"; readonly lines: number }316 | {317 readonly kind: "pair";318 readonly left?: Line;319 readonly right?: Line;320 };321322/**323 * `diff` as split rows: a context line on both sides, and in a change the324 * deletions beside the additions, row for row, the longer side's rest325 * against nothing.326 */327export const splitRows = (diff: FileDiffMetadata): readonly SplitRow[] => {328 const rows: SplitRow[] = [];329 let lastAddition = 0;330331 for (const hunk of diff.hunks) {332 if (hunk.collapsedBefore > 0) {333 rows.push({ kind: "separator", lines: hunk.collapsedBefore });334 }335336 for (const content of hunk.hunkContent) {337 if (content.type === "context") {338 for (let line = 0; line < content.lines; line += 1) {339 const old = content.deletionLineIndex + line;340 const index = content.additionLineIndex + line;341342 rows.push({343 kind: "pair",344 left: {345 kind: "context",346 number: old + 1,347 text: bare(diff.deletionLines[old]),348 },349 right: {350 kind: "context",351 number: index + 1,352 text: bare(diff.additionLines[index]),353 },354 });355 }356 } else {357 const span = Math.max(content.deletions, content.additions);358359 for (let line = 0; line < span; line += 1) {360 const old = content.deletionLineIndex + line;361 const index = content.additionLineIndex + line;362363 const left: Line = {364 kind: "deletion",365 number: old + 1,366 text: bare(diff.deletionLines[old]),367 };368369 const right: Line = {370 kind: "addition",371 number: index + 1,372 text: bare(diff.additionLines[index]),373 };374375 if (line < content.deletions && line < content.additions) {376 rows.push({ kind: "pair", left, right });377 } else if (line < content.deletions) {378 rows.push({ kind: "pair", left });379 } else {380 rows.push({ kind: "pair", right });381 }382 }383 }384 }385386 lastAddition = hunk.additionStart - 1 + hunk.additionCount;387 }388389 const after = diff.isPartial ? 0 : diff.additionLines.length - lastAddition;390391 if (diff.hunks.length > 0 && after > 0 && diff.type !== "deleted") {392 rows.push({ kind: "separator", lines: after });393 }394395 return rows;396};