forked from cflmy/deepseek-harness
feat(preview): show snapshot changes side by side with readable JSONL records
Co-authored-by: yudshj <16971372+yudshj@users.noreply.github.com>
This commit is contained in:
1 parent
3aee25862d
commit
c2651ad028
6 files changed
+465
-194
No files matched your search
@@ -111,7 +111,7 @@ jobs:
|
||||
continue-on-error: true
|
||||
run: >-
|
||||
pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD
|
||||
--out apps/web/dist/snapshot-diff/index.html
|
||||
--out apps/web/dist/snapshot-diff
|
||||
--preview-manifest apps/web/dist/preview/fixtures.json
|
||||
|
||||
- name: Upload to Cloudflare Pages
|
||||
|
||||
@@ -263,6 +263,7 @@
|
||||
"@vitest/coverage-v8": "^4.1.11",
|
||||
"@yao-pkg/pkg": "6.21.0",
|
||||
"@yarnpkg/cli-dist": "4.18.0",
|
||||
"diff": "^9.0.0",
|
||||
"eslint-plugin-sonarjs": "^4.2.0",
|
||||
"execa": "^10.0.1",
|
||||
"zod": "4.6.6",
|
||||
|
||||
Generated
+3
@@ -186,6 +186,9 @@ importers:
|
||||
'@yarnpkg/cli-dist':
|
||||
specifier: 4.18.0
|
||||
version: 4.18.0
|
||||
diff:
|
||||
specifier: ^9.0.0
|
||||
version: 9.0.0
|
||||
eslint-plugin-sonarjs:
|
||||
specifier: ^4.2.0
|
||||
version: 4.2.0(eslint@10.5.0(jiti@2.7.0)(supports-color@9.4.0))
|
||||
|
||||
@@ -91,7 +91,7 @@ describe('PR preview workflow', () => {
|
||||
const steps = preview.steps.map(step => step.name)
|
||||
const page = preview.steps.find(step => step.name === 'Render the snapshot diff page')!
|
||||
expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD'
|
||||
+ ' --out apps/web/dist/snapshot-diff/index.html --preview-manifest apps/web/dist/preview/fixtures.json')
|
||||
+ ' --out apps/web/dist/snapshot-diff --preview-manifest apps/web/dist/preview/fixtures.json')
|
||||
expect(steps.indexOf('Render the snapshot diff page')).toBeGreaterThan(steps.indexOf('Shape the upload'))
|
||||
expect(steps.indexOf('Render the snapshot diff page')).toBeLessThan(steps.indexOf('Upload to Cloudflare Pages'))
|
||||
})
|
||||
|
||||
@@ -1,66 +1,80 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { addPreviewLink, catalogFiles, groupDiffs, limitDiffs, parseUnifiedDiff, renderSnapshotDiffPage } from './snapshot-diff-page.ts'
|
||||
import { addPreviewLink, catalogFiles, groupDiffs, readableUnits, renderSnapshotDiffPage, sideBySide } from './snapshot-diff-page.ts'
|
||||
|
||||
const diff = `diff --git a/snapshots/sdk/text-turn/system-prompt.expected.md b/snapshots/sdk/text-turn/system-prompt.expected.md
|
||||
index 1111111..2222222 100644
|
||||
--- a/snapshots/sdk/text-turn/system-prompt.expected.md
|
||||
+++ b/snapshots/sdk/text-turn/system-prompt.expected.md
|
||||
@@ -1,2 +1,2 @@
|
||||
You are an agent.
|
||||
-Old rule.
|
||||
+New rule.
|
||||
diff --git a/snapshots/web/ptc-round/session.jsonl b/snapshots/web/ptc-round/session.jsonl
|
||||
deleted file mode 100644
|
||||
index 3333333..0000000
|
||||
--- a/snapshots/web/ptc-round/session.jsonl
|
||||
+++ /dev/null
|
||||
@@ -1 +0,0 @@
|
||||
-{"type":"header"}
|
||||
diff --git a/snapshots/web/ptc-round/image.png b/snapshots/web/ptc-round/image.png
|
||||
new file mode 100644
|
||||
index 0000000..4444444
|
||||
Binary files /dev/null and b/snapshots/web/ptc-round/image.png differ
|
||||
diff --git a/snapshots/web/present/workspace.expected/a b/说明.txt b/snapshots/web/present/workspace.expected/a b/说明.txt
|
||||
old mode 100644
|
||||
new mode 100755
|
||||
`
|
||||
|
||||
const file = (path: string, hunks = '') => ({ path, hunks, binary: false, omitted: 0 })
|
||||
const limits = { context: 1, rows: 100, wordDiffChars: 100, timeoutMs: 5000 }
|
||||
const text = (...lines: string[]) => [lines.map(line => `${line}\n`).join('')]
|
||||
|
||||
describe('snapshot diff page', () => {
|
||||
it('splits git diff output into files with their hunks', () => {
|
||||
expect(parseUnifiedDiff(diff)).toEqual([
|
||||
file('snapshots/sdk/text-turn/system-prompt.expected.md', '@@ -1,2 +1,2 @@\n You are an agent.\n-Old rule.\n+New rule.'),
|
||||
file('snapshots/web/ptc-round/session.jsonl', '@@ -1 +0,0 @@\n-{"type":"header"}'),
|
||||
{ ...file('snapshots/web/ptc-round/image.png'), binary: true },
|
||||
file('snapshots/web/present/workspace.expected/a b/说明.txt'),
|
||||
it('renders JSONL records as labelled YAML blocks and keeps other files whole', () => {
|
||||
const jsonl = [
|
||||
'{"type":"user/message","data":{"text":"a\\nb"}}',
|
||||
'{"method":"session.event","params":{"event":{"type":"turn/start"}}}',
|
||||
'{"method":"ping"}',
|
||||
'[1]',
|
||||
'not json',
|
||||
'',
|
||||
].join('\n')
|
||||
expect(readableUnits('s/session.jsonl', jsonl)).toEqual([
|
||||
'# user/message\ntype: user/message\ndata:\n text: |-\n a\n b\n',
|
||||
'# session.event turn/start\nmethod: session.event\nparams:\n event:\n type: turn/start\n',
|
||||
'# ping\nmethod: ping\n',
|
||||
'[1]\n',
|
||||
'not json\n',
|
||||
])
|
||||
expect(parseUnifiedDiff('')).toEqual([])
|
||||
expect(readableUnits('s/prompt.md', 'a\nb')).toEqual(['a\nb'])
|
||||
expect(readableUnits('s/prompt.md', '')).toEqual([])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['a quoted path', 'diff --git "a/snapshots/x\\ty" "b/snapshots/x\\ty"\n'],
|
||||
['unequal header paths', 'diff --git a/snapshots/x b/snapshots/y\n'],
|
||||
['a missing prefix', 'diff --git snapshots/x snapshots/x\n'],
|
||||
])('rejects a header with %s', (_, text) => {
|
||||
expect(() => parseUnifiedDiff(text)).toThrow('unsupported git diff header')
|
||||
it('collapses unchanged runs beyond the context and pairs changed lines with word highlights', () => {
|
||||
const result = sideBySide(text('a', 'b', 'c', 'd', 'old word', 'e', 'f', 'g'), text('a', 'b', 'c', 'd', 'new word', 'e', 'added', 'f', 'g'), limits)
|
||||
expect(result).toEqual({
|
||||
added: 2, removed: 1, omitted: 0,
|
||||
rows: [
|
||||
['skip', 1, 1, ['a', 'b', 'c']],
|
||||
['same', 4, 4, 'd'],
|
||||
['change', 5, 5, [[true, 'old'], [false, ' word']], [[true, 'new'], [false, ' word']]],
|
||||
['same', 6, 6, 'e'],
|
||||
['add', 7, 'added'],
|
||||
['same', 7, 8, 'f'],
|
||||
['same', 8, 9, 'g'],
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('truncates long sections and drops sections past the byte budget of the escaped JSON', () => {
|
||||
const lines = (count: number, line = '+x') => file(`f${count}`, ['@@', ...Array.from({ length: count - 1 }, () => line)].join('\n'))
|
||||
const [long, fits, over] = limitDiffs([lines(150), lines(10), lines(10)], { fileLines: 100, totalBytes: 445 })
|
||||
expect([long?.hunks.split('\n').length, long?.omitted]).toEqual([100, 50])
|
||||
expect([fits?.hunks.split('\n').length, fits?.omitted]).toEqual([10, 0])
|
||||
expect([over?.hunks, over?.omitted]).toEqual(['', 10])
|
||||
// Quotes, `@@`, and nine lines of an escaped newline, `+`, and two six-byte \u003c escapes: 139 bytes.
|
||||
expect(limitDiffs([lines(10, '+<<')], { fileLines: 100, totalBytes: 138 })[0]?.omitted).toBe(10)
|
||||
expect(limitDiffs([lines(10, '+<<')], { fileLines: 100, totalBytes: 139 })[0]?.omitted).toBe(0)
|
||||
it('shows unmatched removed lines and leaves long lines without word highlights', () => {
|
||||
const long = 'x'.repeat(101)
|
||||
expect(sideBySide(text(long, 'gone', 'z'), text(`${long}!`, 'z'), limits).rows).toEqual([
|
||||
['change', 1, 1, long, `${long}!`],
|
||||
['del', 2, 'gone'],
|
||||
['same', 3, 2, 'z'],
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps an inserted JSONL record as one added block when later records also change', () => {
|
||||
const record = (type: string, seq: number) => `{"type":"${type}","seq":${String(seq)},"a":1,"b":2,"c":3}`
|
||||
const before = readableUnits('x.jsonl', [record('one', 1), record('three', 2)].join('\n'))
|
||||
const after = readableUnits('x.jsonl', [record('one', 1), record('two', 2), record('three', 3)].join('\n'))
|
||||
const rows = sideBySide(before, after, { ...limits, context: 0 }).rows ?? []
|
||||
expect(rows.filter(row => row[0] === 'add').map(row => row[2])).toEqual(['# two', 'type: two', 'seq: 2', 'a: 1', 'b: 2', 'c: 3'])
|
||||
expect(rows.filter(row => row[0] === 'change')).toEqual([['change', 9, 15, [[false, 'seq: '], [true, '2']], [[false, 'seq: '], [true, '3']]]])
|
||||
})
|
||||
|
||||
it('reports omitted rows past the limit and no rows when the diff times out', () => {
|
||||
const many = Array.from({ length: 10 }, (_, index) => `line ${String(index)}`)
|
||||
expect(sideBySide([], text(...many), { ...limits, rows: 4 })).toMatchObject({ added: 10, removed: 0, omitted: 6 })
|
||||
expect(sideBySide([], text(...many), { ...limits, rows: 4 }).rows).toHaveLength(4)
|
||||
// The skip row holds lines 1–7 and costs 8, so only it and the next row fit in 9.
|
||||
const collapsed = sideBySide(text('1', '2', '3', '4', '5', '6', '7', '8', 'old', '9'), text('1', '2', '3', '4', '5', '6', '7', '8', 'new', '9'), { ...limits, rows: 9 })
|
||||
expect([collapsed.rows?.map(row => row[0]), collapsed.omitted]).toEqual([['skip', 'same'], 2])
|
||||
const big = Array.from({ length: 4000 }, (_, index) => String(index))
|
||||
expect(sideBySide(text(...big), text(...big.toReversed()), { ...limits, timeoutMs: 0 }))
|
||||
.toEqual({ added: 4000, removed: 4000, omitted: 0 })
|
||||
})
|
||||
|
||||
it('opens on the catalog, then groups scenarios and other files by directory in code point order', () => {
|
||||
const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json']
|
||||
const paths = ['snapshots/web/b/x', 'snapshots/sdk/sdk.snapshot.ts', 'snapshots/AGENTS.md', 'snapshots/web/B/x', 'snapshots/web/b/a/y']
|
||||
expect(groupDiffs([...paths, 'snapshots/web/b/x'].map(path => file(path)), catalog)).toEqual([
|
||||
expect(groupDiffs(paths, catalog)).toEqual([
|
||||
{ title: 'SDK blank Session catalog', paths: catalog },
|
||||
{ title: 'snapshots', paths: ['snapshots/AGENTS.md'] },
|
||||
{ title: 'sdk', paths: ['snapshots/sdk/sdk.snapshot.ts'] },
|
||||
@@ -73,8 +87,8 @@ describe('snapshot diff page', () => {
|
||||
['owns both sidecars', 'profile: sdk\n', 'sdk/text-turn', 'sdk/text-turn'],
|
||||
['names a source in its own suite directory', 'profile: sdk-minimal\nheader:\n toolSchemasSource: other\n', 'sdk/text-turn', 'sdk/other'],
|
||||
['names sources in another suite', 'profile: sdk\nheader:\n systemPromptSource: session/a\n toolSchemasSource: session/b\n', 'session/a', 'session/b'],
|
||||
])('resolves catalog sidecars when the manifest %s', (_, text, prompt, schemas) => {
|
||||
expect(catalogFiles(text)).toEqual({
|
||||
])('resolves catalog sidecars when the manifest %s', (_, manifest, prompt, schemas) => {
|
||||
expect(catalogFiles(manifest)).toEqual({
|
||||
systemPrompt: `snapshots/${prompt}/system-prompt.expected.md`,
|
||||
toolSchemas: `snapshots/${schemas}/tool-schemas.expected.json`,
|
||||
})
|
||||
@@ -83,16 +97,17 @@ describe('snapshot diff page', () => {
|
||||
it.each([
|
||||
['a non-string source', 'profile: sdk\nheader:\n toolSchemasSource: 1\n', 'header.toolSchemasSource must be a non-empty string'],
|
||||
['an empty source', 'header:\n systemPromptSource: ""\n', 'header.systemPromptSource must be a non-empty string'],
|
||||
])('rejects %s', (_, text, message) => {
|
||||
expect(() => catalogFiles(text)).toThrow(message)
|
||||
])('rejects %s', (_, manifest, message) => {
|
||||
expect(() => catalogFiles(manifest)).toThrow(message)
|
||||
})
|
||||
|
||||
it('embeds the data so diff text cannot close the script element', () => {
|
||||
const files = [file('p', '+</script><b>')]
|
||||
const page = renderSnapshotDiffPage(files, [{ title: 't', paths: ['p'] }], 'a → b')
|
||||
it('embeds the index so a path cannot close the script element', () => {
|
||||
const files = [{ path: 'p</script><b>', added: 1, removed: 0 }]
|
||||
const groups = [{ title: 't', paths: ['p</script><b>'] }]
|
||||
const page = renderSnapshotDiffPage(files, groups, 'a → b')
|
||||
expect(page).not.toContain('</script><b>')
|
||||
const data = /<script type="application\/json" id="data">(.*)<\/script>/.exec(page)?.[1] ?? ''
|
||||
expect(JSON.parse(data)).toEqual({ files, groups: [{ title: 't', paths: ['p'] }], heading: 'a → b' })
|
||||
expect(JSON.parse(data)).toEqual({ files, groups, heading: 'a → b' })
|
||||
})
|
||||
|
||||
it('appends the page link to the Preview fixture manifest', () => {
|
||||
|
||||
+387
-135
@@ -1,50 +1,72 @@
|
||||
/**
|
||||
* Renders the PR preview's snapshot diff page: one self-contained HTML file
|
||||
* listing every changed file under `snapshots/` between two revisions, grouped
|
||||
* by scenario directory. The page opens on the SDK blank-Session catalog, the
|
||||
* system prompt and tool schemas the `sdk/text-turn` scenario's first request
|
||||
* carries, and shows "No change" for a catalog file whose content is equal on
|
||||
* both sides.
|
||||
* Renders the PR preview's snapshot diff site: an `index.html` that lists every
|
||||
* changed file under `snapshots/` between two revisions, grouped by scenario
|
||||
* directory, plus one `files/<n>.json` per file holding its side-by-side diff
|
||||
* rows, which the page loads when a group opens. The page opens on the SDK
|
||||
* blank-Session catalog, the system prompt and tool schemas the
|
||||
* `sdk/text-turn` scenario's first request carries, and shows "No change" for
|
||||
* a catalog file whose content is equal on both sides.
|
||||
*
|
||||
* Usage: `tsx scripts/snapshot-diff-page.ts --base <rev> --head <rev> --out <file> [--preview-manifest <fixtures.json>]`.
|
||||
* JSONL files are compared in a readable form: each record becomes a
|
||||
* `# <label>` heading followed by its YAML rendering, so long records span
|
||||
* several lines and multiline strings, such as prompts and runtime context,
|
||||
* appear as text blocks. Records align as units before their lines are
|
||||
* compared, so an inserted record shows as one added block.
|
||||
*
|
||||
* Usage: `tsx scripts/snapshot-diff-page.ts --base <rev> --head <rev> --out <dir> [--preview-manifest <fixtures.json>]`.
|
||||
* `--preview-manifest` adds a link to the page in the Preview source chooser.
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, posix, relative, sep } from 'node:path'
|
||||
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join, posix, relative, sep } from 'node:path'
|
||||
import { parseArgs } from 'node:util'
|
||||
import { diffArrays, diffLines, diffWordsWithSpace } from 'diff'
|
||||
import * as yaml from 'js-yaml'
|
||||
|
||||
/** Scenario whose first request represents a blank SDK Session. */
|
||||
const CATALOG_SCENARIO = 'sdk/text-turn'
|
||||
|
||||
/** Limits on embedded diff text; the page notes how many lines it omits. */
|
||||
/** Limits that keep each per-file data file small enough to load and render. */
|
||||
export interface DiffLimits {
|
||||
/** Hunk lines kept per diff section. */
|
||||
readonly fileLines: number
|
||||
/** UTF-8 bytes of escaped JSON hunk text kept across the page. */
|
||||
readonly totalBytes: number
|
||||
/** Unchanged lines kept around each change before the rest collapse. */
|
||||
readonly context: number
|
||||
/** Rows kept per file, counting each line a collapsed run holds; the page notes how many rows it omits. */
|
||||
readonly rows: number
|
||||
/** Lines longer than this skip word-level highlighting. */
|
||||
readonly wordDiffChars: number
|
||||
/** Milliseconds the line diff may take before the file shows as replaced. */
|
||||
readonly timeoutMs: number
|
||||
}
|
||||
|
||||
/** Keeps the page well under the Cloudflare Pages 25 MiB per-file limit. */
|
||||
const LIMITS: DiffLimits = { fileLines: 2000, totalBytes: 20 * 1024 * 1024 }
|
||||
const LIMITS: DiffLimits = { context: 3, rows: 4000, wordDiffChars: 2000, timeoutMs: 5000 }
|
||||
|
||||
/** One `diff --git` section: a changed file and its unified diff text. */
|
||||
export interface FileDiff {
|
||||
/** Repository-relative path, or `old → new` for a catalog file whose source scenario changed. */
|
||||
/** A cell's text, or text segments whose `true` flag marks changed words. */
|
||||
export type Cell = string | ReadonlyArray<readonly [boolean, string]>
|
||||
|
||||
/**
|
||||
* One side-by-side row: an unchanged line, a changed pair, a line on one side
|
||||
* only, or collapsed unchanged lines that the page can expand.
|
||||
*/
|
||||
export type Row =
|
||||
| readonly ['same', number, number, string]
|
||||
| readonly ['change', number, number, Cell, Cell]
|
||||
| readonly ['del', number, string]
|
||||
| readonly ['add', number, string]
|
||||
| readonly ['skip', number, number, readonly string[]]
|
||||
|
||||
/** One changed file in the page index. */
|
||||
export interface FileEntry {
|
||||
readonly path: string
|
||||
/** Unified diff lines from the first `@@` hunk header, empty for binary or mode-only changes. */
|
||||
readonly hunks: string
|
||||
/** True when git reports a binary change. */
|
||||
readonly binary: boolean
|
||||
/** Hunk lines left out of `hunks` by the limits. */
|
||||
readonly omitted: number
|
||||
readonly added: number
|
||||
readonly removed: number
|
||||
/** Why rows are absent: a binary side, equal content with a changed mode or type, or a diff over the time limit. */
|
||||
readonly note?: 'binary' | 'mode' | 'timeout'
|
||||
}
|
||||
|
||||
/** A selectable entry on the page. */
|
||||
export interface DiffGroup {
|
||||
readonly title: string
|
||||
/** Distinct {@link FileDiff.path} values the group shows, including unchanged ones. */
|
||||
/** Distinct {@link FileEntry.path} values the group shows, including unchanged ones. */
|
||||
readonly paths: readonly string[]
|
||||
}
|
||||
|
||||
@@ -54,70 +76,233 @@ export interface CatalogFiles {
|
||||
readonly toolSchemas: string
|
||||
}
|
||||
|
||||
function hunksOf(lines: readonly string[]): string[] {
|
||||
const start = lines.findIndex(line => line.startsWith('@@'))
|
||||
return start === -1 ? [] : lines.slice(start, lines.at(-1) === '' ? -1 : undefined)
|
||||
}
|
||||
|
||||
function section(path: string, lines: readonly string[]): FileDiff {
|
||||
const hunks = hunksOf(lines)
|
||||
return { path, hunks: hunks.join('\n'), binary: lines.some(line => line.startsWith('Binary files ')), omitted: 0 }
|
||||
/** Names a record by its `type`, the `params.event.type` of a Session event notification, or its `method`. */
|
||||
function recordLabel(record: object): string {
|
||||
const { type, method, params } = record as { type?: unknown; method?: unknown; params?: { event?: { type?: unknown } } }
|
||||
const eventType = params?.event?.type
|
||||
if (typeof type === 'string') return type
|
||||
if (typeof method === 'string') return typeof eventType === 'string' ? `${method} ${eventType}` : method
|
||||
return 'record'
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits git diff output into per-file sections.
|
||||
* @param text - Output of `git -c core.quotePath=false diff --no-color --no-renames --no-ext-diff --src-prefix=a/ --dst-prefix=b/`.
|
||||
* @returns One untruncated entry per `diff --git` section, in output order. A
|
||||
* path that changes between symlink and regular file has two sections.
|
||||
* @throws When a header does not read `diff --git a/<path> b/<path>`, as for a
|
||||
* path git still quotes (one with `"`, `\\`, or a control character).
|
||||
* Splits file content into the units the page aligns before comparing lines.
|
||||
* @param path - Repository-relative path; `.jsonl` selects the record view.
|
||||
* @param text - File content.
|
||||
* @returns The whole content as one unit, or for JSONL one unit per record: a
|
||||
* `# <label>` heading and the record's YAML rendering, ending in a newline. A
|
||||
* line that is not a JSON object stays as written.
|
||||
*/
|
||||
export function parseUnifiedDiff(text: string): FileDiff[] {
|
||||
const files: FileDiff[] = []
|
||||
for (const part of text.split(/^(?=diff --git )/m)) {
|
||||
if (!part.startsWith('diff --git ')) continue
|
||||
const lines = part.split('\n')
|
||||
const header = /^diff --git a\/(.+) b\/\1$/.exec(lines[0] ?? '')
|
||||
if (header?.[1] === undefined) throw new Error(`unsupported git diff header: ${lines[0] ?? ''}`)
|
||||
files.push(section(header[1], lines))
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
function embeddedBytes(text: string): number {
|
||||
return Buffer.byteLength(JSON.stringify(text).replace(/</g, '\\u003c'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the limits in order: each section keeps at most `fileLines` hunk
|
||||
* lines, and a section that would exceed the remaining byte budget keeps none.
|
||||
* @param files - Sections in page order.
|
||||
* @param limits - Per-section line and page byte limits.
|
||||
* @returns Sections with `hunks` cut and `omitted` counting the dropped lines.
|
||||
*/
|
||||
export function limitDiffs(files: readonly FileDiff[], limits: DiffLimits = LIMITS): FileDiff[] {
|
||||
let budget = limits.totalBytes
|
||||
return files.map((file) => {
|
||||
const all = file.hunks === '' ? [] : file.hunks.split('\n')
|
||||
let hunks = all.slice(0, limits.fileLines).join('\n')
|
||||
if (embeddedBytes(hunks) > budget) hunks = ''
|
||||
budget -= embeddedBytes(hunks)
|
||||
const kept = hunks === '' ? 0 : Math.min(all.length, limits.fileLines)
|
||||
return { ...file, hunks, omitted: all.length - kept }
|
||||
export function readableUnits(path: string, text: string): string[] {
|
||||
if (!path.endsWith('.jsonl')) return text === '' ? [] : [text]
|
||||
return text.split('\n').filter(line => line !== '').map((line) => {
|
||||
let record: unknown
|
||||
try {
|
||||
record = JSON.parse(line)
|
||||
} catch {
|
||||
// A line that is not JSON is shown unchanged.
|
||||
return `${line}\n`
|
||||
}
|
||||
if (typeof record !== 'object' || record === null || Array.isArray(record)) return `${line}\n`
|
||||
return `# ${recordLabel(record)}\n${yaml.dump(record, { lineWidth: -1, noRefs: true })}`
|
||||
})
|
||||
}
|
||||
|
||||
interface LineChange {
|
||||
readonly value: string
|
||||
readonly added?: boolean
|
||||
readonly removed?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Units count as the same record when they open with the same line, the
|
||||
* record label, and at least half of the longer one's lines also occur in the other.
|
||||
*/
|
||||
function similar(left: readonly string[], right: readonly string[]): boolean {
|
||||
if (left[0] !== right[0]) return false
|
||||
const other = new Set(right)
|
||||
let shared = 0
|
||||
for (const line of new Set(left)) if (other.has(line)) shared++
|
||||
return shared * 2 >= Math.max(new Set(left).size, other.size)
|
||||
}
|
||||
|
||||
/**
|
||||
* Diffs a run of removed units against a run of added units: units pair up by
|
||||
* {@link similar} in order and each pair is diffed line by line, while
|
||||
* unpaired units stay whole removals or additions.
|
||||
*/
|
||||
function pairedChanges(removed: readonly string[], added: readonly string[], deadline: number): LineChange[] | undefined {
|
||||
if (removed.length === 1 && added.length === 1) return diffLines(removed[0] ?? '', added[0] ?? '', { timeout: remaining(deadline) })
|
||||
const left = removed.map(unit => unit.split('\n'))
|
||||
const right = added.map(unit => unit.split('\n'))
|
||||
const indexes = (count: number) => Array.from({ length: count }, (_, index) => index)
|
||||
const alignment = diffArrays(indexes(removed.length), indexes(added.length), {
|
||||
timeout: remaining(deadline),
|
||||
comparator: (a, b) => similar(left[a] ?? [], right[b] ?? []),
|
||||
})
|
||||
if (alignment === undefined) return undefined
|
||||
const changes: LineChange[] = []
|
||||
let l = 0
|
||||
let r = 0
|
||||
for (const part of alignment) {
|
||||
for (let step = 0; step < part.count; step++) {
|
||||
if (part.removed) changes.push({ value: removed[l++] ?? '', removed: true })
|
||||
else if (part.added) changes.push({ value: added[r++] ?? '', added: true })
|
||||
else {
|
||||
const lines = diffLines(removed[l++] ?? '', added[r++] ?? '', { timeout: remaining(deadline) })
|
||||
if (lines === undefined) return undefined
|
||||
changes.push(...lines)
|
||||
}
|
||||
}
|
||||
}
|
||||
return changes
|
||||
}
|
||||
|
||||
/** Milliseconds left before `deadline`; jsdiff gives up at once when none remain. */
|
||||
function remaining(deadline: number): number {
|
||||
return Math.max(0, deadline - Date.now())
|
||||
}
|
||||
|
||||
/**
|
||||
* Aligns whole units first, so an inserted or deleted record stays one block,
|
||||
* then diffs lines inside each run of changed units.
|
||||
*/
|
||||
function lineChanges(before: readonly string[], after: readonly string[], deadline: number): LineChange[] | undefined {
|
||||
const units = diffArrays([...before], [...after], { timeout: remaining(deadline) })
|
||||
if (units === undefined) return undefined
|
||||
const changes: LineChange[] = []
|
||||
for (let index = 0; index < units.length; index++) {
|
||||
const unit = units[index]
|
||||
const next = units[index + 1]
|
||||
if (unit === undefined) continue
|
||||
if (unit.removed && next?.added) {
|
||||
const paired = pairedChanges(unit.value, next.value, deadline)
|
||||
if (paired === undefined) return undefined
|
||||
changes.push(...paired)
|
||||
index++
|
||||
} else {
|
||||
changes.push({ value: unit.value.join(''), added: unit.added, removed: unit.removed })
|
||||
}
|
||||
}
|
||||
return changes
|
||||
}
|
||||
|
||||
function linesOf(value: string): string[] {
|
||||
const lines = value.split('\n')
|
||||
if (lines.at(-1) === '') lines.pop()
|
||||
return lines
|
||||
}
|
||||
|
||||
/** Joins adjacent unchanged changes so context collapses across unit boundaries. */
|
||||
function mergeCommon(changes: LineChange[] | undefined): LineChange[] | undefined {
|
||||
if (changes === undefined) return undefined
|
||||
const merged: LineChange[] = []
|
||||
for (const change of changes) {
|
||||
const last = merged.at(-1)
|
||||
const common = !change.added && !change.removed
|
||||
if (common && last !== undefined && !last.added && !last.removed) merged[merged.length - 1] = { value: last.value + change.value }
|
||||
else if (change.value !== '') merged.push(change)
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
function wordCells(left: string, right: string, limits: DiffLimits): [Cell, Cell] {
|
||||
if (left.length > limits.wordDiffChars || right.length > limits.wordDiffChars) return [left, right]
|
||||
const parts = diffWordsWithSpace(left, right)
|
||||
return [
|
||||
parts.filter(part => !part.added).map(part => [part.removed, part.value] as const),
|
||||
parts.filter(part => !part.removed).map(part => [part.added, part.value] as const),
|
||||
]
|
||||
}
|
||||
|
||||
/** Rows and line counts for one file; `rows` is absent when the diff timed out. */
|
||||
export interface SideBySide {
|
||||
readonly rows?: Row[]
|
||||
readonly added: number
|
||||
readonly removed: number
|
||||
readonly omitted: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds side-by-side rows for two unit lists from {@link readableUnits}.
|
||||
* Unchanged runs keep `context` lines next to each change and collapse the
|
||||
* rest into `skip` rows; removed and added runs pair up line by line as
|
||||
* `change` rows with word highlights.
|
||||
* @param before - Base units; empty for an added file.
|
||||
* @param after - Head units; empty for a deleted file.
|
||||
* @param limits - Context, row, word-diff, and time limits.
|
||||
* @returns Rows, added and removed line counts, and rows left out by the row
|
||||
* limit, with word highlights only on kept rows; `undefined` rows when the diff exceeded the time limit.
|
||||
*/
|
||||
export function sideBySide(before: readonly string[], after: readonly string[], limits: DiffLimits = LIMITS): SideBySide {
|
||||
const changes = mergeCommon(lineChanges(before, after, Date.now() + limits.timeoutMs))
|
||||
if (changes === undefined) return { added: linesOf(after.join('')).length, removed: linesOf(before.join('')).length, omitted: 0 }
|
||||
const rows: Row[] = []
|
||||
// A row costs 1, and a skip row also costs the lines it holds.
|
||||
let cost = 0
|
||||
let omitted = 0
|
||||
const push = (row: Row) => {
|
||||
const size = row[0] === 'skip' ? 1 + row[3].length : 1
|
||||
if (cost + size > limits.rows) omitted++
|
||||
else {
|
||||
cost += size
|
||||
rows.push(row)
|
||||
}
|
||||
}
|
||||
let left = 1
|
||||
let right = 1
|
||||
let added = 0
|
||||
let removed = 0
|
||||
for (let index = 0; index < changes.length; index++) {
|
||||
const change = changes[index]
|
||||
if (change === undefined) continue
|
||||
const lines = linesOf(change.value)
|
||||
if (!change.added && !change.removed) {
|
||||
const head = index === 0 ? 0 : limits.context
|
||||
const tail = index === changes.length - 1 ? 0 : limits.context
|
||||
if (lines.length <= head + tail + 1) {
|
||||
for (const line of lines) push(['same', left++, right++, line])
|
||||
continue
|
||||
}
|
||||
for (const line of lines.slice(0, head)) push(['same', left++, right++, line])
|
||||
const hidden = lines.slice(head, lines.length - tail)
|
||||
push(['skip', left, right, hidden])
|
||||
left += hidden.length
|
||||
right += hidden.length
|
||||
for (const line of lines.slice(lines.length - tail)) push(['same', left++, right++, line])
|
||||
continue
|
||||
}
|
||||
const next = changes[index + 1]
|
||||
const removedLines = change.removed ? lines : []
|
||||
const addedLines = change.removed && next?.added ? linesOf(next.value) : change.added ? lines : []
|
||||
if (change.removed && next?.added) index++
|
||||
removed += removedLines.length
|
||||
added += addedLines.length
|
||||
for (let line = 0; line < Math.max(removedLines.length, addedLines.length); line++) {
|
||||
const before = removedLines[line]
|
||||
const after = addedLines[line]
|
||||
if (before !== undefined && after !== undefined) push(['change', left++, right++, before, after])
|
||||
else if (before !== undefined) push(['del', left++, before])
|
||||
else if (after !== undefined) push(['add', right++, after])
|
||||
}
|
||||
}
|
||||
const withWords = rows.map((row): Row => row[0] === 'change' && typeof row[3] === 'string' && typeof row[4] === 'string'
|
||||
? ['change', row[1], row[2], ...wordCells(row[3], row[4], limits)]
|
||||
: row)
|
||||
return { rows: withWords, added, removed, omitted }
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups changed files for the page: the catalog first, then one group per
|
||||
* scenario directory (`snapshots/<suite>/<scenario>`) and one per directory
|
||||
* holding other changed files, in code point order.
|
||||
* @param files - Changed files under `snapshots/`.
|
||||
* @param paths - Changed paths under `snapshots/`.
|
||||
* @param catalogPaths - Paths the catalog group shows.
|
||||
* @returns The catalog group followed by the directory groups.
|
||||
*/
|
||||
export function groupDiffs(files: readonly FileDiff[], catalogPaths: readonly string[]): DiffGroup[] {
|
||||
export function groupDiffs(paths: readonly string[], catalogPaths: readonly string[]): DiffGroup[] {
|
||||
const groups = new Map<string, Set<string>>()
|
||||
for (const { path } of files) {
|
||||
for (const path of paths) {
|
||||
const segments = path.split('/')
|
||||
const key = segments.slice(0, segments.length >= 4 ? 3 : -1).join('/')
|
||||
groups.set(key, (groups.get(key) ?? new Set()).add(path))
|
||||
@@ -126,7 +311,7 @@ export function groupDiffs(files: readonly FileDiff[], catalogPaths: readonly st
|
||||
return [
|
||||
{ title: 'SDK blank Session catalog', paths: catalogPaths },
|
||||
...[...groups].sort(([a], [b]) => byCodePoint(a, b))
|
||||
.map(([key, paths]) => ({ title: key.replace(/^snapshots\/?/, '') || 'snapshots', paths: [...paths].sort(byCodePoint) })),
|
||||
.map(([key, members]) => ({ title: key.replace(/^snapshots\/?/, '') || 'snapshots', paths: [...members].sort(byCodePoint) })),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -153,13 +338,14 @@ export function catalogFiles(manifestText: string): CatalogFiles {
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the self-contained page.
|
||||
* @param files - Limited sections from {@link limitDiffs}.
|
||||
* Renders the page shell; file rows load from `files/<index>.json`, where the
|
||||
* index is the file's position in `files`.
|
||||
* @param files - Changed files.
|
||||
* @param groups - Groups from {@link groupDiffs}; the first one opens by default.
|
||||
* @param heading - Revision description shown under the title.
|
||||
* @returns HTML text.
|
||||
*/
|
||||
export function renderSnapshotDiffPage(files: readonly FileDiff[], groups: readonly DiffGroup[], heading: string): string {
|
||||
export function renderSnapshotDiffPage(files: readonly FileEntry[], groups: readonly DiffGroup[], heading: string): string {
|
||||
const data = JSON.stringify({ files, groups, heading }).replace(/</g, '\\u003c')
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
@@ -168,26 +354,38 @@ export function renderSnapshotDiffPage(files: readonly FileDiff[], groups: reado
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Snapshot changes</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; font: 14px/1.45 system-ui, sans-serif; }
|
||||
:root { color-scheme: light dark; font: 14px/1.45 system-ui, sans-serif; --line: #8884; --muted: #888; --add: #2da44e26; --add-word: #2da44e66; --del: #cf222e26; --del-word: #cf222e66; }
|
||||
body { margin: 0; display: grid; grid-template-columns: minmax(200px, 300px) 1fr; height: 100vh; }
|
||||
nav { overflow: auto; border-right: 1px solid #8884; padding: 12px 0; }
|
||||
nav { overflow: auto; border-right: 1px solid var(--line); padding: 12px 0; }
|
||||
nav h1 { font-size: 16px; margin: 0 16px 4px; }
|
||||
nav p { margin: 0 16px 12px; color: #888; font-size: 12px; }
|
||||
nav p { margin: 0 16px 12px; color: var(--muted); font-size: 12px; }
|
||||
nav button { display: flex; justify-content: space-between; gap: 8px; width: 100%; padding: 6px 16px; border: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }
|
||||
nav button:hover { background: #8882; }
|
||||
nav button[aria-current="true"] { background: #4a90e233; font-weight: 600; }
|
||||
nav button span:last-child { color: #888; font-variant-numeric: tabular-nums; }
|
||||
nav hr { border: 0; border-top: 1px solid #8884; margin: 8px 0; }
|
||||
nav hr { border: 0; border-top: 1px solid var(--line); margin: 8px 0; }
|
||||
.stat { font: 12px ui-monospace, monospace; white-space: nowrap; }
|
||||
.stat .a { color: #1f883d; } .stat .r { color: #cf222e; }
|
||||
main { overflow: auto; padding: 16px 24px; }
|
||||
main h2 { font-size: 16px; margin: 0 0 12px; }
|
||||
section { margin-bottom: 20px; border: 1px solid #8884; border-radius: 6px; overflow: hidden; }
|
||||
section h3 { font: 600 13px ui-monospace, monospace; margin: 0; padding: 8px 12px; background: #8881; border-bottom: 1px solid #8884; }
|
||||
pre { margin: 0; font: 12px/1.5 ui-monospace, monospace; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
pre div { padding: 0 12px; }
|
||||
.add { background: #2da44e26; }
|
||||
.del { background: #cf222e26; }
|
||||
.hunk { color: #888; background: #8881; }
|
||||
.empty { padding: 8px 12px; color: #888; }
|
||||
section { margin-bottom: 20px; border: 1px solid var(--line); border-radius: 6px; overflow: hidden; }
|
||||
section h3 { display: flex; justify-content: space-between; gap: 12px; font: 600 13px ui-monospace, monospace; margin: 0; padding: 8px 12px; background: #8881; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
|
||||
table { width: 100%; border-collapse: collapse; table-layout: fixed; font: 12px/1.5 ui-monospace, monospace; }
|
||||
col.n { width: 4.5em; }
|
||||
td { vertical-align: top; padding: 0 8px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
td.n { color: var(--muted); text-align: right; user-select: none; padding-right: 6px; }
|
||||
td.c + td.n { border-left: 1px solid var(--line); }
|
||||
td.del { background: var(--del); } td.add { background: var(--add); }
|
||||
td.del mark { background: var(--del-word); color: inherit; } td.add mark { background: var(--add-word); color: inherit; }
|
||||
td.none { background: #8881; }
|
||||
tr.skip td { padding: 2px 12px; color: var(--muted); background: #8881; }
|
||||
tr.skip button { border: 0; background: none; color: #4a90e2; font: inherit; cursor: pointer; padding: 0; }
|
||||
.empty { padding: 8px 12px; color: var(--muted); }
|
||||
@media (max-width: 900px) {
|
||||
body { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
|
||||
nav { max-height: 30vh; border-right: 0; border-bottom: 1px solid var(--line); }
|
||||
main { padding: 12px; }
|
||||
col.n { width: 3.5em; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -199,39 +397,77 @@ const { files, groups, heading } = JSON.parse(document.getElementById('data').te
|
||||
document.getElementById('heading').textContent = heading
|
||||
const list = document.getElementById('list')
|
||||
const view = document.getElementById('view')
|
||||
const indexOf = new Map(files.map((file, index) => [file.path, index]))
|
||||
function el(tag, props = {}, ...children) {
|
||||
const node = Object.assign(document.createElement(tag), props)
|
||||
node.append(...children)
|
||||
return node
|
||||
}
|
||||
function stat(added, removed) {
|
||||
return el('span', { className: 'stat' }, el('span', { className: 'a', textContent: '+' + added }), ' ', el('span', { className: 'r', textContent: '-' + removed }))
|
||||
}
|
||||
const buttons = groups.map((group, index) => {
|
||||
const button = el('button', { type: 'button', onclick: () => show(index) }, el('span', { textContent: group.title }), el('span', { textContent: String(group.paths.filter(path => files.some(file => file.path === path)).length) }))
|
||||
const changed = group.paths.map(path => files[indexOf.get(path)]).filter(Boolean)
|
||||
const button = el('button', { type: 'button', onclick: () => show(index) }, el('span', { textContent: group.title }),
|
||||
stat(changed.reduce((sum, file) => sum + file.added, 0), changed.reduce((sum, file) => sum + file.removed, 0)))
|
||||
list.append(button)
|
||||
if (index === 0) list.append(el('hr'))
|
||||
return button
|
||||
})
|
||||
if (groups.length === 1) list.append(el('p', { textContent: 'No other snapshot changed.' }))
|
||||
function lineClass(line) {
|
||||
if (line.startsWith('@@')) return 'hunk'
|
||||
if (line.startsWith('+')) return 'add'
|
||||
if (line.startsWith('-')) return 'del'
|
||||
return ''
|
||||
function cell(value) {
|
||||
if (typeof value === 'string') return [value]
|
||||
return value.map(([changed, text]) => changed ? el('mark', { textContent: text }) : text)
|
||||
}
|
||||
function render(file) {
|
||||
if (file.binary) return [el('div', { className: 'empty', textContent: 'Binary file changed' })]
|
||||
const nodes = file.hunks ? [el('pre', {}, ...file.hunks.split('\\n').map(line => el('div', { className: lineClass(line), textContent: line || ' ' })))] : []
|
||||
if (file.omitted) nodes.push(el('div', { className: 'empty', textContent: file.omitted + ' more diff lines omitted; see the pull request diff' }))
|
||||
return nodes.length ? nodes : [el('div', { className: 'empty', textContent: 'File mode or type changed' })]
|
||||
function td(className, ...children) { return el('td', { className }, ...children) }
|
||||
function rowNodes(row) {
|
||||
switch (row[0]) {
|
||||
case 'same': return [el('tr', {}, td('n', String(row[1])), td('c', row[3]), td('n', String(row[2])), td('c', row[3]))]
|
||||
case 'change': return [el('tr', {}, td('n', String(row[1])), td('c del', ...cell(row[3])), td('n', String(row[2])), td('c add', ...cell(row[4])))]
|
||||
case 'del': return [el('tr', {}, td('n', String(row[1])), td('c del', row[2]), td('n'), td('c none'))]
|
||||
case 'add': return [el('tr', {}, td('n'), td('c none'), td('n', String(row[1])), td('c add', row[2]))]
|
||||
case 'skip': {
|
||||
const tr = el('tr', { className: 'skip' })
|
||||
const expand = el('button', { type: 'button', textContent: 'Show ' + row[3].length + ' unchanged lines' })
|
||||
expand.onclick = () => tr.replaceWith(...row[3].flatMap((line, i) => rowNodes(['same', row[1] + i, row[2] + i, line])))
|
||||
tr.append(el('td', { colSpan: 4 }, expand))
|
||||
return [tr]
|
||||
}
|
||||
}
|
||||
return []
|
||||
}
|
||||
function show(index) {
|
||||
function table(data) {
|
||||
const body = el('tbody', {}, ...data.rows.flatMap(rowNodes))
|
||||
const node = el('table', {}, el('colgroup', {}, el('col', { className: 'n' }), el('col'), el('col', { className: 'n' }), el('col')), body)
|
||||
return data.omitted ? [node, el('div', { className: 'empty', textContent: data.omitted + ' more rows omitted; see the pull request diff' })] : [node]
|
||||
}
|
||||
async function fileBody(index) {
|
||||
const file = files[index]
|
||||
if (file.note === 'binary') return [el('div', { className: 'empty', textContent: 'Binary file changed' })]
|
||||
if (file.note === 'mode') return [el('div', { className: 'empty', textContent: 'Only the file mode or type changed' })]
|
||||
if (file.note === 'timeout') return [el('div', { className: 'empty', textContent: 'Diff too large to compute; see the pull request diff' })]
|
||||
const response = await fetch('files/' + index + '.json')
|
||||
if (!response.ok) return [el('div', { className: 'empty', textContent: 'Could not load this diff (' + response.status + ')' })]
|
||||
const data = await response.json()
|
||||
return table(data)
|
||||
}
|
||||
let current = 0
|
||||
async function show(index) {
|
||||
current = index
|
||||
const group = groups[index]
|
||||
buttons.forEach((button, i) => button.setAttribute('aria-current', String(i === index)))
|
||||
history.replaceState(null, '', '#' + encodeURIComponent(group.title))
|
||||
view.replaceChildren(el('h2', { textContent: group.title }))
|
||||
for (const path of group.paths) {
|
||||
const sections = files.filter(candidate => candidate.path === path)
|
||||
const bodies = sections.length === 0 ? [el('div', { className: 'empty', textContent: 'No change' })] : sections.flatMap(render)
|
||||
view.append(el('section', {}, el('h3', { textContent: path }), ...bodies))
|
||||
const fileIndex = indexOf.get(path)
|
||||
const file = files[fileIndex]
|
||||
const section = el('section', {}, el('h3', {}, el('span', { textContent: path }), file ? stat(file.added, file.removed) : ''))
|
||||
view.append(section)
|
||||
if (!file) { section.append(el('div', { className: 'empty', textContent: 'No change' })); continue }
|
||||
const body = el('div', { className: 'empty', textContent: 'Loading…' })
|
||||
section.append(body)
|
||||
fileBody(fileIndex).then(nodes => { if (current === index) body.replaceWith(...nodes) },
|
||||
error => { body.textContent = 'Could not load this diff: ' + error })
|
||||
}
|
||||
}
|
||||
const initial = groups.findIndex(group => '#' + encodeURIComponent(group.title) === location.hash)
|
||||
@@ -253,48 +489,64 @@ export function addPreviewLink(manifestText: string, href: string): string {
|
||||
return `${JSON.stringify({ ...manifest, links: [...manifest.links ?? [], { label: 'Snapshot changes', href }] }, null, 2)}\n`
|
||||
}
|
||||
|
||||
function git(...args: string[]): string {
|
||||
return execFileSync('git', args, { encoding: 'utf8', maxBuffer: 1 << 30 })
|
||||
function git(...args: string[]): Buffer {
|
||||
return execFileSync('git', args, { maxBuffer: 1 << 30 })
|
||||
}
|
||||
|
||||
const DIFF = ['-c', 'core.quotePath=false', 'diff', '--no-color', '--no-renames', '--no-ext-diff', '--src-prefix=a/', '--dst-prefix=b/', '--unified=5']
|
||||
/** Reads a blob, or returns an empty buffer when the path is absent at `rev`. */
|
||||
function blob(rev: string, path: string): Buffer {
|
||||
const entry = git('ls-tree', '-z', rev, '--', path).toString('utf8')
|
||||
return entry === '' ? Buffer.alloc(0) : git('cat-file', 'blob', `${rev}:${path}`)
|
||||
}
|
||||
|
||||
/** Requires a regular file, because git diffs a symlink as its target path rather than the content it names. */
|
||||
/** Requires a regular file, because a symlink blob holds its target path rather than the content it names. */
|
||||
function assertRegularFile(rev: string, path: string): void {
|
||||
const mode = git('ls-tree', rev, '--', path).split(' ')[0]
|
||||
const mode = git('ls-tree', rev, '--', path).toString('utf8').split(' ')[0]
|
||||
if (mode !== '100644' && mode !== '100755') throw new Error(`catalog file ${path} at ${rev} is not a regular file (mode ${mode || 'missing'})`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Diffs one catalog sidecar. When its source scenario moved, the blobs are
|
||||
* compared directly under an `old → new` label, because neither file changed.
|
||||
*/
|
||||
function catalogDiff(base: string, head: string, from: string, to: string): { path: string; extra?: FileDiff } {
|
||||
assertRegularFile(base, from)
|
||||
assertRegularFile(head, to)
|
||||
if (from === to) return { path: to }
|
||||
const path = `${from} → ${to}`
|
||||
const text = git(...DIFF, `${base}:${from}`, `${head}:${to}`)
|
||||
return text === '' ? { path } : { path, extra: section(path, text.split('\n')) }
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
const { values } = parseArgs({ options: { 'base': { type: 'string' }, 'head': { type: 'string' }, 'out': { type: 'string' }, 'preview-manifest': { type: 'string' } } })
|
||||
const { base, head, out } = values
|
||||
if (!base || !head || !out) throw new Error('usage: snapshot-diff-page.ts --base <rev> --head <rev> --out <file> [--preview-manifest <fixtures.json>]')
|
||||
const short = (rev: string) => git('rev-parse', '--short', rev).trim()
|
||||
const changed = parseUnifiedDiff(git(...DIFF, base, head, '--', 'snapshots/'))
|
||||
const manifestAt = (rev: string) => catalogFiles(git('show', `${rev}:snapshots/${CATALOG_SCENARIO}/snapshot.yml`))
|
||||
if (!base || !head || !out) throw new Error('usage: snapshot-diff-page.ts --base <rev> --head <rev> --out <dir> [--preview-manifest <fixtures.json>]')
|
||||
const short = (rev: string) => git('rev-parse', '--short', rev).toString('utf8').trim()
|
||||
const changed = git('diff', '-z', '--name-only', '--no-renames', base, head, '--', 'snapshots/').toString('utf8').split('\0').filter(path => path !== '')
|
||||
const manifestAt = (rev: string) => catalogFiles(git('show', `${rev}:snapshots/${CATALOG_SCENARIO}/snapshot.yml`).toString('utf8'))
|
||||
const from = manifestAt(base)
|
||||
const to = manifestAt(head)
|
||||
const catalog = [catalogDiff(base, head, from.systemPrompt, to.systemPrompt), catalogDiff(base, head, from.toolSchemas, to.toolSchemas)]
|
||||
const files = limitDiffs([...catalog.flatMap(entry => entry.extra ? [entry.extra] : []), ...changed])
|
||||
const page = renderSnapshotDiffPage(files, groupDiffs(changed, catalog.map(entry => entry.path)), `${short(base)} → ${short(head)}`)
|
||||
mkdirSync(dirname(out), { recursive: true })
|
||||
writeFileSync(out, page)
|
||||
type Side = [rev: string, path: string]
|
||||
const pairs: Array<{ path: string; before: Side; after: Side }> = changed
|
||||
.map(path => ({ path, before: [base, path], after: [head, path] }))
|
||||
const catalog = (['systemPrompt', 'toolSchemas'] as const).map((key) => {
|
||||
assertRegularFile(base, from[key])
|
||||
assertRegularFile(head, to[key])
|
||||
if (from[key] === to[key]) return to[key]
|
||||
// The source scenario moved: compare the two files under an `old → new` label.
|
||||
const path = `${from[key]} → ${to[key]}`
|
||||
if (!blob(base, from[key]).equals(blob(head, to[key]))) pairs.unshift({ path, before: [base, from[key]], after: [head, to[key]] })
|
||||
return path
|
||||
})
|
||||
// Only the outputs this script writes are removed, so a mistaken --out cannot delete other files.
|
||||
rmSync(join(out, 'files'), { recursive: true, force: true })
|
||||
rmSync(join(out, 'index.html'), { force: true })
|
||||
mkdirSync(join(out, 'files'), { recursive: true })
|
||||
const files: FileEntry[] = pairs.map(({ path, before, after }, index) => {
|
||||
const [left, right] = [blob(...before), blob(...after)]
|
||||
if (left.equals(right)) return { path, added: 0, removed: 0, note: 'mode' }
|
||||
if (left.includes(0) || right.includes(0)) return { path, added: 0, removed: 0, note: 'binary' }
|
||||
const [leftText, rightText] = [left.toString('utf8'), right.toString('utf8')]
|
||||
let [leftUnits, rightUnits] = [readableUnits(before[1], leftText), readableUnits(after[1], rightText)]
|
||||
// A change the record view drops, such as blank lines, is shown in the raw text.
|
||||
if (leftUnits.join('') === rightUnits.join('')) [leftUnits, rightUnits] = [[leftText], [rightText]]
|
||||
const result = sideBySide(leftUnits, rightUnits)
|
||||
if (result.rows === undefined) return { path, added: result.added, removed: result.removed, note: 'timeout' }
|
||||
writeFileSync(join(out, 'files', `${String(index)}.json`), JSON.stringify({ rows: result.rows, omitted: result.omitted }))
|
||||
return { path, added: result.added, removed: result.removed }
|
||||
})
|
||||
writeFileSync(join(out, 'index.html'), renderSnapshotDiffPage(files, groupDiffs(changed, catalog), `${short(base)} → ${short(head)}`))
|
||||
const manifest = values['preview-manifest']
|
||||
if (manifest) {
|
||||
const href = `${relative(dirname(manifest), dirname(out)).split(sep).join(posix.sep)}/`
|
||||
const href = `${relative(dirname(manifest), out).split(sep).join(posix.sep)}/`
|
||||
writeFileSync(manifest, addPreviewLink(readFileSync(manifest, 'utf8'), href))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user