Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(lab): parseUnifiedDiff reads a patch into the DiffViewer file model (#7568)

Cindy Zhang0788e9b9319f
diff --git a/packages/lab/src/DiffViewer/diffTypes.ts b/packages/lab/src/DiffViewer/diffTypes.ts
new file mode 100644
index 0000000000..2ce23a7a50
--- /dev/null
+++ b/packages/lab/src/DiffViewer/diffTypes.ts
@@ -0,0 +1,73 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file diffTypes.ts
+ * @input None (type-only module)
+ * @output Exports the structured diff model DiffViewer renders: DiffViewerFile,
+ * DiffViewerHunk, DiffViewerLine, DiffViewerLineKind, DiffViewerFileStatus,
+ * DiffViewerSide, DiffViewerLineRef
+ * @position Lab data model; produced by parseUnifiedDiff (or built by hand) and
+ * consumed by DiffViewer
+ *
+ * SYNC: When modified, update:
+ * - /packages/lab/src/DiffViewer/index.ts (type exports)
+ */
+
+/** What one line of a hunk does: adds, removes, or keeps a line. */
+export type DiffViewerLineKind = 'added' | 'removed' | 'context';
+
+/** How the file changed as a whole. */
+export type DiffViewerFileStatus = 'added' | 'deleted' | 'modified' | 'renamed';
+
+/**
+ * Which version of the file a line number belongs to: `old` is the original
+ * (left in split view), `new` the changed version (right in split view).
+ */
+export type DiffViewerSide = 'old' | 'new';
+
+/** One line of a hunk, without its leading `+`/`-`/space glyph. */
+export interface DiffViewerLine {
+ kind: DiffViewerLineKind;
+ /** The line's text with the diff glyph removed. */
+ content: string;
+ /** 1-based line number in the old file; `null` for an added line. */
+ oldLineNumber: number | null;
+ /** 1-based line number in the new file; `null` for a removed line. */
+ newLineNumber: number | null;
+}
+
+/** One `@@` hunk: a run of changed lines with their surrounding context. */
+export interface DiffViewerHunk {
+ /** The hunk header as written, e.g. `@@ -12,7 +12,9 @@ function save()`. */
+ header: string;
+ oldStart: number;
+ oldLines: number;
+ newStart: number;
+ newLines: number;
+ lines: DiffViewerLine[];
+}
+
+/** One file's changes. */
+export interface DiffViewerFile {
+ /** Path before the change; `null` when the file was added. */
+ oldPath: string | null;
+ /** Path after the change; `null` when the file was deleted. */
+ newPath: string | null;
+ status: DiffViewerFileStatus;
+ /** True when the patch reports a binary change with no line hunks. */
+ isBinary: boolean;
+ hunks: DiffViewerHunk[];
+}
+
+/**
+ * Identifies one line of a rendered diff for annotations and line-number
+ * clicks. Every line has exactly one ref, the same in unified and split view,
+ * so `side` + `lineNumber` is a stable anchor (e.g. for a review comment): an
+ * added line is `new`, a removed line is `old`, and a context line is `new`.
+ */
+export interface DiffViewerLineRef {
+ side: DiffViewerSide;
+ lineNumber: number;
+ line: DiffViewerLine;
+ hunkIndex: number;
+}
diff --git a/packages/lab/src/DiffViewer/index.ts b/packages/lab/src/DiffViewer/index.ts
new file mode 100644
index 0000000000..369bcefea0
--- /dev/null
+++ b/packages/lab/src/DiffViewer/index.ts
@@ -0,0 +1,20 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file index.ts
+ * @input Imports from parseUnifiedDiff.ts and diffTypes.ts
+ * @output Exports the structured diff model and the unified-diff parser
+ * @position Entry point for the DiffViewer folder; re-exported by
+ * /packages/lab/src/index.ts
+ */
+
+export {parseUnifiedDiff} from './parseUnifiedDiff';
+export type {
+ DiffViewerFile,
+ DiffViewerFileStatus,
+ DiffViewerHunk,
+ DiffViewerLine,
+ DiffViewerLineKind,
+ DiffViewerLineRef,
+ DiffViewerSide,
+} from './diffTypes';
diff --git a/packages/lab/src/DiffViewer/parseUnifiedDiff.test.ts b/packages/lab/src/DiffViewer/parseUnifiedDiff.test.ts
new file mode 100644
index 0000000000..4be397950d
--- /dev/null
+++ b/packages/lab/src/DiffViewer/parseUnifiedDiff.test.ts
@@ -0,0 +1,397 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import {parseUnifiedDiff} from './parseUnifiedDiff';
+
+const GIT_PATCH = `diff --git a/src/math.ts b/src/math.ts
+index 3b18e51..a9c2f7d 100644
+--- a/src/math.ts
++++ b/src/math.ts
+@@ -1,5 +1,6 @@
+ export function add(a: number, b: number) {
+- return a + b;
++ const sum = a + b;
++ return sum;
+ }
+
+ export const ZERO = 0;
+@@ -10,3 +11,3 @@ export function sub(a: number, b: number) {
+ // trailing
+-const old = 1;
++const next = 1;
+ // end
+diff --git a/README.md b/README.md
+new file mode 100644
+index 0000000..e69de29
+--- /dev/null
++++ b/README.md
+@@ -0,0 +1,2 @@
++# Title
++Body
+diff --git a/old/name.ts b/new/name.ts
+similarity index 100%
+rename from old/name.ts
+rename to new/name.ts
+diff --git a/logo.png b/logo.png
+index 1111111..2222222 100644
+Binary files a/logo.png and b/logo.png differ
+diff --git a/gone.txt b/gone.txt
+deleted file mode 100644
+index e69de29..0000000
+--- a/gone.txt
++++ /dev/null
+@@ -1 +0,0 @@
+-bye
+`;
+
+describe('parseUnifiedDiff', () => {
+ it('splits a git patch into one file per diff header', () => {
+ const files = parseUnifiedDiff(GIT_PATCH);
+ expect(files.map(f => f.status)).toEqual([
+ 'modified',
+ 'added',
+ 'renamed',
+ 'modified',
+ 'deleted',
+ ]);
+ });
+
+ it('numbers lines from the hunk header on each side', () => {
+ const [math] = parseUnifiedDiff(GIT_PATCH);
+ expect(math.oldPath).toBe('src/math.ts');
+ expect(math.newPath).toBe('src/math.ts');
+ expect(math.hunks).toHaveLength(2);
+ const [first, second] = math.hunks;
+ expect(first.header).toBe('@@ -1,5 +1,6 @@');
+ expect(
+ first.lines.map(l => [l.kind, l.oldLineNumber, l.newLineNumber]),
+ ).toEqual([
+ ['context', 1, 1],
+ ['removed', 2, null],
+ ['added', null, 2],
+ ['added', null, 3],
+ ['context', 3, 4],
+ ['context', 4, 5],
+ ['context', 5, 6],
+ ]);
+ expect(first.lines[1].content).toBe(' return a + b;');
+ // An empty context line keeps an empty content string.
+ expect(first.lines[5].content).toBe('');
+ expect(second.header).toBe(
+ '@@ -10,3 +11,3 @@ export function sub(a: number, b: number) {',
+ );
+ expect(second.lines[1]).toEqual({
+ kind: 'removed',
+ content: 'const old = 1;',
+ oldLineNumber: 11,
+ newLineNumber: null,
+ });
+ });
+
+ it('reads added, renamed, binary, and deleted files', () => {
+ const [, added, renamed, binary, deleted] = parseUnifiedDiff(GIT_PATCH);
+ expect(added).toMatchObject({oldPath: null, newPath: 'README.md'});
+ expect(added.hunks[0].lines.map(l => l.newLineNumber)).toEqual([1, 2]);
+
+ expect(renamed).toMatchObject({
+ oldPath: 'old/name.ts',
+ newPath: 'new/name.ts',
+ hunks: [],
+ });
+
+ expect(binary).toMatchObject({isBinary: true, hunks: []});
+
+ expect(deleted).toMatchObject({oldPath: 'gone.txt', newPath: null});
+ expect(deleted.hunks[0].lines).toEqual([
+ {kind: 'removed', content: 'bye', oldLineNumber: 1, newLineNumber: null},
+ ]);
+ });
+
+ it('reads classic diff -u output with timestamps', () => {
+ const files = parseUnifiedDiff(
+ [
+ '--- a.txt\t2024-01-01 00:00:00.000000000 +0000',
+ '+++ b.txt\t2024-01-02 00:00:00.000000000 +0000',
+ '@@ -1 +1 @@',
+ '-one',
+ '+uno',
+ ].join('\n'),
+ );
+ expect(files).toHaveLength(1);
+ expect(files[0]).toMatchObject({
+ oldPath: 'a.txt',
+ newPath: 'b.txt',
+ status: 'modified',
+ });
+ });
+
+ it('marks a file renamed only from git rename lines', () => {
+ const files = parseUnifiedDiff(
+ [
+ // diff -ruN between two trees: an edit and an -N creation.
+ 'diff -ruN old/app.ini new/app.ini',
+ '--- old/app.ini\t2024-01-01 00:00:00.000000000 +0000',
+ '+++ new/app.ini\t2024-01-02 00:00:00.000000000 +0000',
+ '@@ -1 +1 @@',
+ '-debug=false',
+ '+debug=true',
+ 'diff -ruN old/extra.ini new/extra.ini',
+ '--- old/extra.ini\t1970-01-01 00:00:00.000000000 +0000',
+ '+++ new/extra.ini\t2024-01-02 00:00:00.000000000 +0000',
+ '@@ -0,0 +1 @@',
+ '+level=2',
+ // git diff --no-index between two unrelated files.
+ 'diff --git a/before.txt b/after.txt',
+ 'index 1111111..2222222 100644',
+ '--- a/before.txt',
+ '+++ b/after.txt',
+ '@@ -1 +1 @@',
+ '-x',
+ '+y',
+ ].join('\n'),
+ );
+ expect(
+ files.map(file => [file.oldPath, file.newPath, file.status]),
+ ).toEqual([
+ ['old/app.ini', 'new/app.ini', 'modified'],
+ ['old/extra.ini', 'new/extra.ini', 'modified'],
+ ['before.txt', 'after.txt', 'modified'],
+ ]);
+ });
+
+ it.each([
+ ['no closing differ', `Binary files ${'a and '.repeat(33_000)}tail`],
+ ['a CR before differ', `Binary files ${'a and '.repeat(33_000)}\r differ`],
+ [
+ 'a U+2028 before differ',
+ `Binary files ${'a and '.repeat(33_000)}\u2028 differ`,
+ ],
+ ])(
+ 'parses a long crafted binary-looking line with %s in linear time',
+ (_, crafted) => {
+ // A commit-message line in `git format-patch` output, before any diff.
+ // A backtracking pattern takes seconds on lines like these.
+ const start = performance.now();
+ const files = parseUnifiedDiff(
+ [
+ 'Subject: [PATCH] update x',
+ '',
+ crafted,
+ '---',
+ 'diff --git a/x.ts b/x.ts',
+ '--- a/x.ts',
+ '+++ b/x.ts',
+ '@@ -1 +1 @@',
+ '-a',
+ '+b',
+ ].join('\n'),
+ );
+ expect(performance.now() - start).toBeLessThan(500);
+ // A line that ends in ` differ` has the binary-line shape, so it may
+ // read as a binary entry of its own; the real file is unaffected.
+ expect(files.at(-1)).toMatchObject({
+ newPath: 'x.ts',
+ isBinary: false,
+ });
+ expect(files.at(-1)?.hunks).toHaveLength(1);
+ },
+ );
+
+ it('reads copies from their copy lines, paths with spaces included', () => {
+ // An exact copy has no ---/+++ lines, so only the copy lines name it.
+ const files = parseUnifiedDiff(
+ [
+ 'diff --git a/my file.ts b/my copy.ts',
+ 'similarity index 100%',
+ 'copy from my file.ts',
+ 'copy to my copy.ts',
+ 'diff --git a/notes.txt "b/caf\\303\\251 notes.txt"',
+ 'similarity index 100%',
+ 'copy from notes.txt',
+ 'copy to "caf\\303\\251 notes.txt"',
+ ].join('\n'),
+ );
+ expect(
+ files.map(file => [file.oldPath, file.newPath, file.status]),
+ ).toEqual([
+ ['my file.ts', 'my copy.ts', 'modified'],
+ ['notes.txt', 'café notes.txt', 'modified'],
+ ]);
+ });
+
+ it('reads a headerless binary line from diff -r as a file of its own', () => {
+ const files = parseUnifiedDiff(
+ [
+ 'Binary files old/first.png and new/first.png differ',
+ 'diff -ruN old/a.txt new/a.txt',
+ '--- old/a.txt\t2024-01-01 00:00:00.000000000 +0000',
+ '+++ new/a.txt\t2024-01-02 00:00:00.000000000 +0000',
+ '@@ -1 +1 @@',
+ '-one',
+ '+uno',
+ 'Binary files old/x.png and new/x.png differ',
+ 'Binary files /dev/null and new/y.png differ',
+ 'diff -ruN old/z.txt new/z.txt',
+ '--- old/z.txt\t2024-01-01 00:00:00.000000000 +0000',
+ '+++ new/z.txt\t2024-01-02 00:00:00.000000000 +0000',
+ '@@ -1 +1 @@',
+ '-two',
+ '+dos',
+ ].join('\n'),
+ );
+ expect(
+ files.map(file => [
+ file.oldPath,
+ file.newPath,
+ file.status,
+ file.isBinary,
+ file.hunks.length,
+ ]),
+ ).toEqual([
+ ['old/first.png', 'new/first.png', 'modified', true, 0],
+ ['old/a.txt', 'new/a.txt', 'modified', false, 1],
+ ['old/x.png', 'new/x.png', 'modified', true, 0],
+ [null, 'new/y.png', 'added', true, 0],
+ ['old/z.txt', 'new/z.txt', 'modified', false, 1],
+ ]);
+ });
+
+ it('starts a new file at each ---/+++ pair after a hunk', () => {
+ const files = parseUnifiedDiff(
+ [
+ '--- a/x.ts',
+ '+++ b/x.ts',
+ '@@ -1 +1 @@',
+ '-a',
+ '+b',
+ '--- a/y.ts',
+ '+++ b/y.ts',
+ '@@ -1 +1 @@',
+ '-c',
+ '+d',
+ ].join('\n'),
+ );
+ expect(files.map(f => f.newPath)).toEqual(['x.ts', 'y.ts']);
+ });
+
+ it('keeps a removed line that starts with -- inside a hunk', () => {
+ const [file] = parseUnifiedDiff(
+ ['@@ -1,2 +1 @@', '--- a comment', '+++ b', '-x', ''].join('\n'),
+ );
+ expect(file.hunks[0].lines.map(l => [l.kind, l.content])).toEqual([
+ ['removed', '-- a comment'],
+ ['added', '++ b'],
+ ['removed', 'x'],
+ ]);
+ });
+
+ it('reads a bare hunk with no file header', () => {
+ const [file] = parseUnifiedDiff('@@ -3,2 +3,2 @@\n a\n-b\n+c\n');
+ expect(file).toMatchObject({
+ oldPath: null,
+ newPath: null,
+ status: 'modified',
+ });
+ expect(file.hunks[0].lines).toHaveLength(3);
+ });
+
+ it('skips "No newline at end of file" markers', () => {
+ const [file] = parseUnifiedDiff(
+ '@@ -1 +1 @@\n-a\n\\ No newline at end of file\n+b\n\\ No newline at end of file\n',
+ );
+ expect(file.hunks[0].lines.map(l => l.kind)).toEqual(['removed', 'added']);
+ });
+
+ it('accepts CRLF line endings', () => {
+ const [file] = parseUnifiedDiff('@@ -1 +1 @@\r\n-a\r\n+b\r\n');
+ expect(file.hunks[0].lines.map(l => l.content)).toEqual(['a', 'b']);
+ });
+
+ it('reads a path with spaces from the git header when no other line names it', () => {
+ const files = parseUnifiedDiff(
+ [
+ 'diff --git a/assets/my logo.png b/assets/my logo.png',
+ 'index 1111111..2222222 100644',
+ 'Binary files a/assets/my logo.png and b/assets/my logo.png differ',
+ 'diff --git a/scripts/run me.sh b/scripts/run me.sh',
+ 'old mode 100644',
+ 'new mode 100755',
+ 'diff --git a/no space.txt b/no space.txt',
+ 'deleted file mode 100644',
+ 'index e69de29..0000000',
+ ].join('\n'),
+ );
+ expect(files).toEqual([
+ {
+ oldPath: 'assets/my logo.png',
+ newPath: 'assets/my logo.png',
+ status: 'modified',
+ isBinary: true,
+ hunks: [],
+ },
+ {
+ oldPath: 'scripts/run me.sh',
+ newPath: 'scripts/run me.sh',
+ status: 'modified',
+ isBinary: false,
+ hunks: [],
+ },
+ {
+ oldPath: 'no space.txt',
+ newPath: null,
+ status: 'deleted',
+ isBinary: false,
+ hunks: [],
+ },
+ ]);
+ });
+
+ it('takes a renamed path with spaces from its rename lines', () => {
+ const [file] = parseUnifiedDiff(
+ [
+ 'diff --git a/old name.ts b/new name.ts',
+ 'similarity index 100%',
+ 'rename from old name.ts',
+ 'rename to new name.ts',
+ ].join('\n'),
+ );
+ expect(file).toMatchObject({
+ oldPath: 'old name.ts',
+ newPath: 'new name.ts',
+ status: 'renamed',
+ });
+ });
+
+ it('decodes git-quoted paths with non-ASCII and escaped characters', () => {
+ const files = parseUnifiedDiff(
+ [
+ 'diff --git "a/docs/caf\\303\\251.md" "b/docs/caf\\303\\251.md"',
+ 'index 1111111..2222222 100644',
+ '--- "a/docs/caf\\303\\251.md"',
+ '+++ "b/docs/caf\\303\\251.md"',
+ '@@ -1 +1 @@',
+ '-old',
+ '+new',
+ 'diff --git "a/img/\\346\\227\\245 \\"one\\".png" "b/img/\\346\\227\\245 \\"one\\".png"',
+ 'Binary files "a/img/\\346\\227\\245 \\"one\\".png" and "b/img/\\346\\227\\245 \\"one\\".png" differ',
+ 'diff --git a/notes.txt "b/caf\\303\\251 notes.txt"',
+ 'similarity index 100%',
+ 'rename from notes.txt',
+ 'rename to "caf\\303\\251 notes.txt"',
+ ].join('\n'),
+ );
+ expect(
+ files.map(file => [file.oldPath, file.newPath, file.status]),
+ ).toEqual([
+ ['docs/café.md', 'docs/café.md', 'modified'],
+ ['img/日 "one".png', 'img/日 "one".png', 'modified'],
+ ['notes.txt', 'café notes.txt', 'renamed'],
+ ]);
+ expect(files[1].isBinary).toBe(true);
+ });
+
+ it('returns no files for text that is not a diff', () => {
+ expect(parseUnifiedDiff('')).toEqual([]);
+ expect(parseUnifiedDiff('hello\nworld')).toEqual([]);
+ });
+});
diff --git a/packages/lab/src/DiffViewer/parseUnifiedDiff.ts b/packages/lab/src/DiffViewer/parseUnifiedDiff.ts
new file mode 100644
index 0000000000..e65eb53c6f
--- /dev/null
+++ b/packages/lab/src/DiffViewer/parseUnifiedDiff.ts
@@ -0,0 +1,436 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file parseUnifiedDiff.ts
+ * @input A unified diff / patch string (`git diff`, `diff -u`, or a bare hunk)
+ * @output Exports parseUnifiedDiff(patch) → DiffViewerFile[]
+ * @position Lab utility; turns patch text into the structured model DiffViewer
+ * renders
+ *
+ * Tolerant by design: unknown header lines are skipped, a hunk whose counts
+ * run short ends where its lines end, and input with no recognizable file or
+ * hunk returns an empty array. It never throws.
+ *
+ * SYNC: When modified, update:
+ * - /packages/lab/src/DiffViewer/parseUnifiedDiff.test.ts
+ */
+
+import type {
+ DiffViewerFile,
+ DiffViewerFileStatus,
+ DiffViewerHunk,
+} from './diffTypes';
+
+const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
+const GIT_HEADER_PREFIX = 'diff --git ';
+const BINARY_PREFIX = 'Binary files ';
+const BINARY_SUFFIX = ' differ';
+const BINARY_SEPARATOR = ' and ';
+
+/**
+ * The two paths of a `Binary files X and Y differ` line, or null when the
+ * line is not one. Plain string matching, not a regex, so any line (however
+ * long, whatever characters it holds) is read in one pass. Like the greedy
+ * pattern it replaces, the separator is the last ` and `.
+ */
+function parseBinaryLine(
+ line: string,
+): {oldPath: string; newPath: string} | null {
+ if (!line.startsWith(BINARY_PREFIX) || !line.endsWith(BINARY_SUFFIX)) {
+ return null;
+ }
+ const middle = line.slice(
+ BINARY_PREFIX.length,
+ line.length - BINARY_SUFFIX.length,
+ );
+ const split = middle.lastIndexOf(BINARY_SEPARATOR);
+ if (split <= 0 || split + BINARY_SEPARATOR.length >= middle.length) {
+ return null;
+ }
+ return {
+ oldPath: middle.slice(0, split),
+ newPath: middle.slice(split + BINARY_SEPARATOR.length),
+ };
+}
+
+const C_ESCAPES: Record<string, number> = {
+ a: 0x07,
+ b: 0x08,
+ t: 0x09,
+ n: 0x0a,
+ v: 0x0b,
+ f: 0x0c,
+ r: 0x0d,
+ '"': 0x22,
+ '\\': 0x5c,
+};
+
+const utf8 = new TextDecoder();
+const utf8Encoder = new TextEncoder();
+
+/**
+ * Read a git C-style quoted path starting at `start` (the opening quote).
+ * Git quotes a path that holds non-ASCII bytes or special characters and
+ * writes those bytes as octal escapes (`"caf\303\251.md"`), so the escapes
+ * are collected as bytes and decoded as UTF-8. Returns the path and the index
+ * just past the closing quote, or null when the quote never closes.
+ */
+function readQuoted(
+ text: string,
+ start: number,
+): {value: string; end: number} | null {
+ const bytes: number[] = [];
+ let i = start + 1;
+ while (i < text.length) {
+ const ch = text[i];
+ if (ch === '"') {
+ return {value: utf8.decode(new Uint8Array(bytes)), end: i + 1};
+ }
+ if (ch === '\\' && i + 1 < text.length) {
+ const next = text[i + 1];
+ const octal = /^[0-7]{3}/.exec(text.slice(i + 1, i + 4));
+ if (octal != null) {
+ bytes.push(parseInt(octal[0], 8));
+ i += 4;
+ continue;
+ }
+ if (next in C_ESCAPES) {
+ bytes.push(C_ESCAPES[next]);
+ i += 2;
+ continue;
+ }
+ }
+ // Any other character stands for itself (as UTF-8 bytes).
+ const codePoint = text.codePointAt(i) ?? 0;
+ const char = String.fromCodePoint(codePoint);
+ bytes.push(...utf8Encoder.encode(char));
+ i += char.length;
+ }
+ return null;
+}
+
+/** The path written in `raw`, unquoted and decoded when git quoted it. */
+function unquotePath(raw: string): string {
+ if (raw.startsWith('"')) {
+ const quoted = readQuoted(raw, 0);
+ if (quoted != null) {
+ return quoted.value;
+ }
+ }
+ return raw;
+}
+
+function stripPrefix(path: string, prefix: 'a/' | 'b/'): string {
+ return path.startsWith(prefix) ? path.slice(prefix.length) : path;
+}
+
+/**
+ * The two paths of a `diff --git` line. Git quotes a path that holds special
+ * or non-ASCII characters; quoted paths are read whole and decoded. An
+ * unquoted path may hold spaces, so a space can look like the separator: when
+ * both sides name the same path (every change except a rename) the separator
+ * is the middle space. A rename writes `rename from` / `rename to` lines,
+ * which replace these paths, so the first-space split is only a fallback.
+ */
+function parseGitHeader(
+ line: string,
+): {oldPath: string; newPath: string} | null {
+ if (!line.startsWith(GIT_HEADER_PREFIX)) {
+ return null;
+ }
+ const rest = line.slice(GIT_HEADER_PREFIX.length);
+ const paths = (left: string, right: string) => ({
+ oldPath: stripPrefix(left, 'a/'),
+ newPath: stripPrefix(right, 'b/'),
+ });
+
+ if (rest.startsWith('"')) {
+ const left = readQuoted(rest, 0);
+ if (left != null && rest[left.end] === ' ') {
+ return paths(left.value, unquotePath(rest.slice(left.end + 1)));
+ }
+ }
+ if (rest.endsWith('"')) {
+ // Only the new side is quoted: it starts at the last ` "` that reads to
+ // the end of the line as one quoted path.
+ for (
+ let split = rest.lastIndexOf(' "');
+ split > 0;
+ split = rest.lastIndexOf(' "', split - 1)
+ ) {
+ const right = readQuoted(rest, split + 1);
+ if (right != null && right.end === rest.length) {
+ return paths(rest.slice(0, split), right.value);
+ }
+ }
+ }
+ if (rest.length % 2 === 1) {
+ const middle = (rest.length - 1) / 2;
+ const left = rest.slice(0, middle);
+ const right = rest.slice(middle + 1);
+ if (
+ rest[middle] === ' ' &&
+ stripPrefix(left, 'a/') === stripPrefix(right, 'b/')
+ ) {
+ return paths(left, right);
+ }
+ }
+ const space = rest.indexOf(' ');
+ return space <= 0 ? null : paths(rest.slice(0, space), rest.slice(space + 1));
+}
+
+interface MutableFile {
+ oldPath: string | null;
+ newPath: string | null;
+ status: DiffViewerFileStatus | null;
+ isBinary: boolean;
+ hunks: DiffViewerHunk[];
+}
+
+function emptyFile(): MutableFile {
+ return {
+ oldPath: null,
+ newPath: null,
+ status: null,
+ isBinary: false,
+ hunks: [],
+ };
+}
+
+/**
+ * `a/src/x.ts` → `src/x.ts`; `/dev/null` → null; drops a trailing
+ * tab+timestamp and decodes a quoted path.
+ */
+function cleanPath(raw: string, prefix: 'a/' | 'b/'): string | null {
+ let path = unquotePath(raw.split('\t')[0].trim());
+ if (path === '/dev/null') {
+ return null;
+ }
+ if (path.startsWith(prefix)) {
+ path = path.slice(prefix.length);
+ }
+ return path;
+}
+
+function finalize(file: MutableFile): DiffViewerFile {
+ let status = file.status;
+ if (status == null) {
+ if (file.oldPath == null && file.newPath != null) {
+ status = 'added';
+ } else if (file.newPath == null && file.oldPath != null) {
+ status = 'deleted';
+ } else {
+ // Only git's rename lines say a file moved. Two different paths
+ // without them (`diff -u a.orig a`, `diff -ruN old new`, a copy) are an
+ // edit between two files, so both paths are kept.
+ status = 'modified';
+ }
+ }
+ return {
+ oldPath: status === 'added' ? null : file.oldPath,
+ newPath: status === 'deleted' ? null : file.newPath,
+ status,
+ isBinary: file.isBinary,
+ hunks: file.hunks,
+ };
+}
+
+function hasContent(file: MutableFile): boolean {
+ return (
+ file.hunks.length > 0 ||
+ file.isBinary ||
+ file.oldPath != null ||
+ file.newPath != null ||
+ file.status != null
+ );
+}
+
+/**
+ * Parse a unified diff into one {@link DiffViewerFile} per file.
+ *
+ * Accepts `git diff` output (with `diff --git`, mode, rename, copy, and
+ * binary lines), classic `diff -u` output (`---`/`+++` pairs), several files in one
+ * patch, and a bare `@@` hunk with no file header (returned as one file with
+ * null paths). Input it cannot read yields `[]`; it never throws.
+ *
+ * @example
+ * ```
+ * const files = parseUnifiedDiff(patch);
+ * files.map((file) => <DiffViewer key={file.newPath ?? file.oldPath} file={file} />);
+ * ```
+ */
+export function parseUnifiedDiff(patch: string): DiffViewerFile[] {
+ const lines = patch.split('\n').map(line => line.replace(/\r$/, ''));
+ const files: DiffViewerFile[] = [];
+ let file: MutableFile | null = null;
+ let hunk: DiffViewerHunk | null = null;
+ let oldRemaining = 0;
+ let newRemaining = 0;
+ let oldLine = 0;
+ let newLine = 0;
+
+ const flush = () => {
+ if (file != null && hasContent(file)) {
+ files.push(finalize(file));
+ }
+ file = null;
+ hunk = null;
+ };
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+
+ // Inside a hunk: consume body lines until both counts are spent.
+ if (hunk != null && (oldRemaining > 0 || newRemaining > 0)) {
+ const glyph = line[0];
+ if (glyph === '\\') {
+ // "\ No newline at end of file" — annotates the previous line.
+ continue;
+ }
+ if (glyph === '+') {
+ hunk.lines.push({
+ kind: 'added',
+ content: line.slice(1),
+ oldLineNumber: null,
+ newLineNumber: newLine++,
+ });
+ newRemaining--;
+ continue;
+ }
+ if (glyph === '-') {
+ hunk.lines.push({
+ kind: 'removed',
+ content: line.slice(1),
+ oldLineNumber: oldLine++,
+ newLineNumber: null,
+ });
+ oldRemaining--;
+ continue;
+ }
+ if (glyph === ' ' || line === '') {
+ // Some tools strip the trailing space of an empty context line.
+ if (line === '' && i === lines.length - 1) {
+ continue;
+ }
+ hunk.lines.push({
+ kind: 'context',
+ content: line.slice(1),
+ oldLineNumber: oldLine++,
+ newLineNumber: newLine++,
+ });
+ oldRemaining--;
+ newRemaining--;
+ continue;
+ }
+ // Anything else ends a short hunk; fall through and read it as a header.
+ hunk = null;
+ }
+ if (hunk != null && line.startsWith('\\')) {
+ continue;
+ }
+
+ const gitPaths = parseGitHeader(line);
+ if (gitPaths != null) {
+ flush();
+ file = emptyFile();
+ file.oldPath = gitPaths.oldPath;
+ file.newPath = gitPaths.newPath;
+ continue;
+ }
+
+ if (
+ line.startsWith('--- ') &&
+ (lines[i + 1]?.startsWith('+++ ') ?? false)
+ ) {
+ // A `---`/`+++` pair opens a new file unless it belongs to a
+ // `diff --git` header whose hunks have not started yet. A binary entry
+ // never takes a pair: in `diff -r` output it was a file of its own.
+ if (file == null || file.hunks.length > 0 || file.isBinary) {
+ flush();
+ file = emptyFile();
+ }
+ const current: MutableFile = file;
+ current.oldPath = cleanPath(line.slice(4), 'a/');
+ current.newPath = cleanPath(lines[i + 1].slice(4), 'b/');
+ if (current.oldPath == null && current.status == null) {
+ current.status = 'added';
+ } else if (current.newPath == null && current.status == null) {
+ current.status = 'deleted';
+ }
+ i++;
+ continue;
+ }
+
+ const header = HUNK_HEADER.exec(line);
+ if (header) {
+ file ??= emptyFile();
+ const oldStart = Number(header[1]);
+ const oldLines = header[2] == null ? 1 : Number(header[2]);
+ const newStart = Number(header[3]);
+ const newLines = header[4] == null ? 1 : Number(header[4]);
+ const next: DiffViewerHunk = {
+ header: line,
+ oldStart,
+ oldLines,
+ newStart,
+ newLines,
+ lines: [],
+ };
+ file.hunks.push(next);
+ hunk = next;
+ oldRemaining = oldLines;
+ newRemaining = newLines;
+ // A zero-length side's start names the line *before* the hunk.
+ oldLine = oldLines === 0 ? oldStart + 1 : oldStart;
+ newLine = newLines === 0 ? newStart + 1 : newStart;
+ continue;
+ }
+
+ // GNU `diff -r` reports a binary file with this one line and no header,
+ // so unless it belongs to a `diff --git` header still being read (no
+ // hunks yet, not already binary), it is a file of its own.
+ const binary = parseBinaryLine(line);
+ if (
+ binary != null &&
+ (file == null || file.hunks.length > 0 || file.isBinary)
+ ) {
+ flush();
+ const own = emptyFile();
+ own.oldPath = cleanPath(binary.oldPath, 'a/');
+ own.newPath = cleanPath(binary.newPath, 'b/');
+ own.isBinary = true;
+ file = own;
+ continue;
+ }
+
+ if (file == null) {
+ continue;
+ }
+ const current: MutableFile = file;
+ if (line.startsWith('new file mode')) {
+ current.status = 'added';
+ } else if (line.startsWith('deleted file mode')) {
+ current.status = 'deleted';
+ } else if (line.startsWith('rename from ')) {
+ current.oldPath = unquotePath(line.slice('rename from '.length));
+ current.status = 'renamed';
+ } else if (line.startsWith('rename to ')) {
+ current.newPath = unquotePath(line.slice('rename to '.length));
+ current.status = 'renamed';
+ } else if (line.startsWith('copy from ')) {
+ // A copy keeps its source, so it reads as an edit from the source path
+ // to the new one; these lines also fix paths the header split wrongly.
+ current.oldPath = unquotePath(line.slice('copy from '.length));
+ } else if (line.startsWith('copy to ')) {
+ current.newPath = unquotePath(line.slice('copy to '.length));
+ } else if (
+ line.startsWith('Binary files ') ||
+ line === 'GIT binary patch'
+ ) {
+ current.isBinary = true;
+ }
+ }
+
+ flush();
+ return files;
+}
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index 7da5ac1a29..c10b47561e 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -258,6 +258,18 @@ export {
type LogStreamLevel,
} from './LogStream';
+// DiffViewer — the structured diff model and the unified-diff parser
+export {
+ parseUnifiedDiff,
+ type DiffViewerFile,
+ type DiffViewerFileStatus,
+ type DiffViewerHunk,
+ type DiffViewerLine,
+ type DiffViewerLineKind,
+ type DiffViewerLineRef,
+ type DiffViewerSide,
+} from './DiffViewer';
+
// MobileTokenizer — Lab prototype (stack layer 1) of the touch Tokenizer
// flow: summary trigger + stacked manage/add BottomSheets. Graduates to
// Core Tokenizer presentation="bottom-sheet" (stack layer 2).