diff --git a/README.md b/README.md index 465c2bf..255317f 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,11 @@ and writes `evidence.html` there: one self-contained page (a Parity / Differs / banner, your verdict, crops embedded) to attach to a ticket or publish as proof: [docs/output.md](https://github.com/tmashara/renderdiff/blob/main/docs/output.md#evidencehtml). +`renderdiff merge --out ` writes the full run's results to a new +out dir with the shots a partial run also took (say, a few routes rerun under a new mask) +replaced by its, and its other shots added. Each merged shot carries `from`: +[docs/output.md](https://github.com/tmashara/renderdiff/blob/main/docs/output.md#merge). + ## Why a clean result is trustworthy - **Refuses to start** unless both origins answer: two error pages would score ~100%. diff --git a/docs/output.md b/docs/output.md index f552b69..88a9a73 100644 --- a/docs/output.md +++ b/docs/output.md @@ -278,12 +278,27 @@ rewrites `report.html` from it, and writes `evidence.html` beside it: one file w outside references, so it can be attached to a ticket or published on its own. It opens with a banner: **Parity** (every shot clean or accepted, no errors), **Differs** (a shot that would exit 1), or **Not verified** (errors, unstable pixels, failed assets, diffs under -`--threshold`, or a `--rerun-failed` run that reused shots). Then the `renderdiff:` line, +`--threshold`, a `--rerun-failed` run that reused shots, or a merged run). Then the `renderdiff:` line, the verdict file as plain text, coverage (clean and accepted routes, errors, stale accepts), and a card per shot that isn't clean, then one per accepted shot, with crops embedded as WebP. Crops past 12MB, or missing from the out dir, are left out and the banner says so. Build it after a fresh full run. +## merge + +`renderdiff merge --out ` writes a new out dir: the full run's +results, each shot the partial run also took replaced by the partial run's (files included), +and the partial run's other shots added after them. No browser. Each shot taken from the +partial run gets `from`, that run's `generatedAt`. `meta` is the full run's, with `widths`, +`masks`, `hideSelectors` and `blockUrlPatterns` the union of both, and `rightReplayedFrom` +recomputed; the summary is recomputed against the full run's threshold. Each shot keeps the +`accepted` flag its own run gave it: `renderdiff.accepted.json` is not reread. The shots +were taken at different times, so `evidence.html` says Not verified; chain +`renderdiff report --verdict …` for one. Exits 2 when the two runs compare different +origins, `--out` is or is inside an input or holds files renderdiff didn't write, a referenced file is missing, or two shots would +write the same file (run both into one `--out` instead). A merged out dir can't be continued +with `--rerun-failed`: rerun into a new `--out` and merge again. + ## results.json Written on every run, errors included, one result per line (so `grep '"url":"/about"'` @@ -310,6 +325,7 @@ pulls a route), scores rounded down to four decimals (so a shot that differs nev "results": [ { "url": "/about", "left": "/about", "right": "/about", // a pair: "/a::/b", "/a", "/b" + "from": "…", // renderdiff merge: generatedAt of the run this shot came from; absent otherwise "selector": null, "hook": false, // hook: a before or beforeShot hook ran "width": 1440, "status": "compared", "score": 0.9714, // share of measured pixels that match diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index 20c58c4..f64e984 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -222,7 +222,7 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so | --- | --- | | 0 | No unaccepted shot differs (with `--threshold`: none scores below it) and no route errored. Unstable pixels or a failed asset alone exit 0: read their rows. | | 1 | An unaccepted shot differs (with `--threshold`: scores below it; `--threshold 0` never fails). Also on an `--accept` run for what can't be accepted. Wins over 3. | -| 2 | Bad arguments or config; an origin not responding; a bad storage state or `renderdiff.accepted.json`; an out dir holding files renderdiff didn't write; `--rerun-failed` that doesn't repeat the last run. | +| 2 | Bad arguments or config; an origin not responding; a bad storage state or `renderdiff.accepted.json`; an out dir holding files renderdiff didn't write; `--rerun-failed` that doesn't repeat the last run; `merge` refusing. | | 3 | A route errored (unmeasured), or the run crashed (e.g. no browser). | ## Iterating @@ -231,6 +231,8 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so (differences, unstable shots, failed assets, errors), merging back into results.json. Same origins, routes, widths, config (masks, hooks, hidden selectors, CSS, storage state, `--computed`) and version as the run it continues, or it exits 2. +- **Hand-picked reruns with a changed config** (a new mask for a few routes): run them into a + new `--out`, then `renderdiff merge --out `. - **`--cache-right`** replays the right side's recorded traffic (`/.cache/`, kept by the wipe) for up to an hour, if the recording covers every shot; otherwise loads live and records. The page still renders live, so `dom` and the refusals hold, but a deploy to the reference @@ -303,6 +305,15 @@ the verdict file as plain text, coverage, and cards for shots that aren't clean, accepted ones, with crops embedded (past 12MB or missing, left out and noted). No external references. Exits 2 without `results.json` or a readable verdict file. +## `merge` + +`renderdiff merge --out `, no browser: the full run's results +with each shot the partial run also took replaced by its (files too), the rest added; each +such shot has `from` (that run's `generatedAt`). Masks, hidden selectors, blocked URLs and +widths are unioned in `meta`; accepted flags stay as each run set them. `evidence.html` says +Not verified. Exits 2 on different origins, an `--out` that is or is inside an input or holds foreign +files, or two shots writing one file. A merged out dir refuses `--rerun-failed`. + ## results.json For scripts and drilling into one route; the loop doesn't need it. One result per line, so diff --git a/src/cli.ts b/src/cli.ts index c69baa4..4c8e5b8 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -181,6 +181,7 @@ const HELP = ` renderdiff http://localhost:3000 https://example.com / /about renderdiff http://localhost:3000 https://example.com /pricing::/plans renderdiff report [--verdict ] [--title ] + renderdiff merge --out An argument starting with http:// or https:// is an origin: the first is left (your change), the second right (the reference); or pass --left / --right. A route is a @@ -204,6 +205,9 @@ const HELP = ` evidence.html beside it: one self-contained page (crops embedded) with a parity banner and the --verdict file's text. + renderdiff merge writes 's results to --out with each shot also + has replaced by the partial run's, and its other shots added. Both must compare the same origins. + Writes report.html, results.json and crops of each change to --out. Exits 1 if any shot differs and isn't accepted (with --threshold, only if one scores below it; --threshold 0 never fails on a diff), 3 if a route errored (unmeasured) or the run @@ -385,7 +389,33 @@ async function report(argv: string[]): Promise { } } +/** `renderdiff merge --out `: no browser, so never exit 1 or 3. */ +async function merge(argv: string[]): Promise { + try { + const dirs: string[] = []; + let out: string | undefined; + for (let i = 0; i < argv.length; i++) { + const v = argv[i]!; + if (v === "--out") { + out = argv[++i]; + if (out === undefined) throw new Error("--out needs a value"); + } else if (v.startsWith("-") || dirs.length === 2) + throw new Error(`unexpected argument: ${v}`); + else dirs.push(v); + } + if (dirs.length !== 2 || !out) + throw new Error("usage: renderdiff merge --out "); + const { merge } = await import("./run.ts"); + await merge(dirs[0]!, dirs[1]!, out); + process.exit(0); + } catch (e) { + console.error(`✗ ${e instanceof Error ? e.message : String(e)}`); + process.exit(2); + } +} + if (process.argv[2] === "report") await report(process.argv.slice(3)); +if (process.argv[2] === "merge") await merge(process.argv.slice(3)); let args: Args; try { diff --git a/src/report.ts b/src/report.ts index 7e7b742..410db66 100644 --- a/src/report.ts +++ b/src/report.ts @@ -36,6 +36,8 @@ interface BaseResult { /** A `before` or `beforeShot` hook ran on both sides before the shot, so the page was measured in its state. */ hook: boolean; width: number; + /** With `renderdiff merge`: generatedAt of the run the shot came from; absent for the run in `meta`. */ + from?: string; } /** A route that was captured on both sides and diffed. */ @@ -667,11 +669,15 @@ export async function writeEvidence( "shot(s) differ under threshold", ), ...count(meta.rerun?.reused ?? 0, "shot(s) reused by --rerun-failed"), + ...count(results.filter((r) => r.from).length, "shot(s) merged from a later run"), ...count(omitted, "crop(s) omitted (over the size budget or missing)"), ]; const [cls, label] = compared.some((r) => fails(r, meta.threshold)) ? ["bad", "Differs"] - : !results.length || meta.rerun?.reused || !results.every(reusable) + : !results.length || + meta.rerun?.reused || + results.some((r) => r.from) || + !results.every(reusable) ? ["warn", "Not verified"] : ["good", "Parity"]; diff --git a/src/run.ts b/src/run.ts index 50ca74e..1974ee8 100644 --- a/src/run.ts +++ b/src/run.ts @@ -26,6 +26,7 @@ import { fails, fmtPixelFindings, stats, + writeEvidence, writeReport, writeResults, type ComparedResult, @@ -160,6 +161,8 @@ function previous(file: string, now: Record): Results | string } catch { return `${file} is not valid JSON; run without --rerun-failed`; } + if (prev.results?.some((r) => r.from)) + return `${file} was written by renderdiff merge; rerun into a new --out and merge again`; const was: Record = { ...prev.meta, routes: [...new Set(prev.results?.map(name))], @@ -677,6 +680,100 @@ export async function run({ return below.length ? 1 : results.some((r) => r.status === "error") ? 3 : 0; } +function readResults(dir: string): Results { + const file = path.join(dir, "results.json"); + if (!fs.existsSync(file)) throw new Error(`no ${file}; run renderdiff with --out ${dir} first`); + try { + return JSON.parse(fs.readFileSync(file, "utf8")); + } catch { + throw new Error(`${file} is not valid JSON`); + } +} + +/** `renderdiff merge`: the full run's results with the partial run's shots replacing or added. */ +export async function merge(fullDir: string, partialDir: string, outDir: string): Promise { + const full = readResults(fullDir); + const partial = readResults(partialDir); + for (const side of ["left", "right"] as const) { + if (full.meta[side] !== partial.meta[side]) + throw new Error( + `${side} differs: ${full.meta[side]} in ${fullDir}, ${partial.meta[side]} in ${partialDir}`, + ); + } + const real = (p: string): string => { + try { + return fs.realpathSync.native(p); + } catch { + return path.join(real(path.dirname(path.resolve(p))), path.basename(p)); + } + }; + for (const dir of [fullDir, partialDir]) { + const rel = path.relative(real(dir), real(outDir)); + if (!rel || (rel.split(path.sep)[0] !== ".." && !path.isAbsolute(rel))) + throw new Error(`--out ${outDir} is or is inside ${dir}; pass a new directory`); + } + if (!wipeable(outDir)) + throw new Error( + `output directory ${outDir} holds files renderdiff didn't write — ` + + `refusing to wipe it. Pass --out with a new or empty directory.`, + ); + + const key = (r: RouteResult) => `${name(r)}@${r.width}`; + const taken = new Map( + partial.results.map((r) => [key(r), { ...r, from: r.from ?? partial.meta.generatedAt }]), + ); + const results = full.results.map((r) => taken.get(key(r)) ?? r); + const replaced = results.filter((r) => taken.has(key(r))).length; + const kept = new Set(full.results.map(key)); + results.push(...[...taken.values()].filter((r) => !kept.has(key(r)))); + + const copies = new Map(); + for (const r of results) { + const src = taken.has(key(r)) ? partialDir : fullDir; + for (const f of files(r)) { + if (!fs.existsSync(path.join(src, f))) throw new Error(`${path.join(src, f)} is missing`); + const had = copies.get(f); + if (had) + throw new Error(`${had.shot} and ${key(r)} both write ${f}; rerun both into one --out`); + copies.set(f, { src, shot: key(r) }); + } + } + + if (fs.existsSync(outDir)) { + for (const f of fs.readdirSync(outDir)) + fs.rmSync(path.join(outDir, f), { recursive: true, force: true }); + } + fs.mkdirSync(outDir, { recursive: true }); + for (const [f, { src }] of copies) fs.copyFileSync(path.join(src, f), path.join(outDir, f)); + + const union = (a: T[], b: T[]) => [ + ...new Map([...a, ...b].map((v) => [JSON.stringify(v), v])).values(), + ]; + const replays = results.flatMap((r) => + r.status === "compared" && r.rightReplayedFrom ? [r.rightReplayedFrom] : [], + ); + const meta = { + ...full.meta, + widths: union(full.meta.widths, partial.meta.widths), + masks: union(full.meta.masks, partial.meta.masks), + hideSelectors: union(full.meta.hideSelectors, partial.meta.hideSelectors), + blockUrlPatterns: union(full.meta.blockUrlPatterns, partial.meta.blockUrlPatterns), + rightReplayedFrom: replays.sort()[0] ?? null, + }; + const stale = [ + ...(full.summary.stale ?? []).filter((a) => !taken.has(`${a.route}@${a.width}`)), + ...(partial.summary.stale ?? []), + ]; + await writeReport(results, meta, outDir, stale); + const resultsPath = writeResults(results, meta, outDir, stale); + await writeEvidence(readResults(outDir), outDir, null); + console.log( + `merged ${taken.size} shot(s) from ${partialDir} (${replaced} replaced, ` + + `${taken.size - replaced} added) into ${outDir}`, + ); + console.log(compact(results, [...new Set(results.map(name))], resultsPath, meta.threshold)); +} + const browserOf = (l: { browser: Browser; channel: string | null }) => ({ name: l.channel ?? "chromium", version: l.browser.version(), diff --git a/tests/unit/report.test.ts b/tests/unit/report.test.ts index 5d0c390..286d2d9 100644 --- a/tests/unit/report.test.ts +++ b/tests/unit/report.test.ts @@ -11,12 +11,13 @@ import { verdict, writeEvidence, writeReport, + writeResults, type ComparedResult, type Results, type RouteResult, type RunMeta, } from "../../src/report.ts"; -import { cleanupTempDirs, tempDir } from "../helpers/cli.ts"; +import { cleanupTempDirs, runCli, tempDir } from "../helpers/cli.ts"; after(cleanupTempDirs); @@ -254,3 +255,116 @@ describe("writeReport", () => { assert.doesNotMatch(html, / { + const imgs = (stem: string) => ({ + left: `${stem}.left.png`, + right: `${stem}.right.png`, + diff: `${stem}.diff.png`, + }); + const crop = (p: string) => ({ ...(differs("/") as ComparedResult).crops[0]!, path: p }); + const files = (r: RouteResult) => + r.status === "compared" + ? [...Object.values(r.images), ...r.crops.map((c) => c.path)] + : (r.frames ?? []); + + function outDir(tag: string, results: RouteResult[], m: Partial = {}) { + const d = path.join(tempDir(), "out"); + fs.mkdirSync(d); + for (const r of results) for (const f of files(r)) fs.writeFileSync(path.join(d, f), tag); + writeResults(results, meta({ generatedAt: `${tag}-at`, widths: [1440, 375], ...m }), d, []); + return d; + } + + const full = () => + outDir("full", [ + shot("/", { + score: 0.9, + diffPixels: 100, + images: imgs("index.1440"), + crops: [crop("index.1440.c1.png"), crop("index.1440.c2.png")], + }), + shot("/", { width: 375, images: imgs("index.375") }), + shot("/a", { images: imgs("a.1440") }), + ]); + const partial = (extra: RouteResult[] = [], m: Partial = {}) => + outDir( + "partial", + [ + shot("/", { images: imgs("index.1440") }), + { + ...shot("/b"), + status: "error", + error: "unsettled", + frames: ["b.1440.left.unsettled-a.png", "b.1440.left.unsettled-b.png"], + } as RouteResult, + ...extra, + ], + { masks: [{ urlPath: "/", reason: "r" }], ...m }, + ); + const merge = (a: string, b: string, out: string) => + runCli(["merge", a, b, "--out", out], { noOut: true }); + + test("replaces matching shots, adds the rest, and copies only what results.json references", async () => { + const [a, b] = [full(), partial()]; + const out = path.join(tempDir(), "merged"); + const r = await merge(a, b, out); + assert.equal(r.code, 0, r.stderr); + assert.match(r.stdout, /merged 2 shot\(s\) .*\(1 replaced, 1 added\)/); + const got: Results = JSON.parse(fs.readFileSync(path.join(out, "results.json"), "utf8")); + assert.deepEqual( + got.results.map((x) => [x.url, x.width, x.from]), + [ + ["/", 1440, "partial-at"], + ["/", 375, undefined], + ["/a", 1440, undefined], + ["/b", 1440, "partial-at"], + ], + ); + assert.equal(got.summary.differing, 0); + assert.deepEqual(got.meta.masks, [{ urlPath: "/", reason: "r" }]); + assert.equal(got.meta.generatedAt, "full-at"); + const read = (f: string) => fs.readFileSync(path.join(out, f), "utf8"); + assert.equal(read("index.1440.left.png"), "partial"); + assert.equal(read("index.375.left.png"), "full"); + assert.equal(read("b.1440.left.unsettled-b.png"), "partial"); + assert.equal(fs.existsSync(path.join(out, "index.1440.c2.png")), false); + assert.ok(fs.existsSync(path.join(out, "report.html"))); + assert.equal(banner(read("evidence.html")), "Not verified"); + assert.match(read("evidence.html"), /2 shot\(s\) merged from a later run/); + assert.equal((await merge(a, b, out)).code, 0); + }); + + test("refuses other origins, an --out at or in an input, a directory it didn't write, and a missing file", async () => { + const [a, b] = [full(), partial()]; + const other = partial([], { right: "https://other.example" }); + assert.match((await merge(a, other, path.join(tempDir(), "o"))).stderr, /✗ right differs/); + const self = await merge(a, b, a); + assert.equal(self.code, 2); + assert.match(self.stderr, /is or is inside/); + const link = path.join(tempDir(), "link"); + fs.symlinkSync(a, link); + assert.match((await merge(a, b, `${link}/`)).stderr, /is or is inside/); + assert.match((await merge(a, b, path.join(b, "sub"))).stderr, /is or is inside/); + const kept = path.join(tempDir(), "kept"); + assert.equal((await merge(a, b, kept)).code, 0); + fs.rmSync(path.join(b, "index.1440.left.png")); + assert.match((await merge(a, b, kept)).stderr, /index\.1440\.left\.png is missing/); + assert.ok(fs.existsSync(path.join(kept, "results.json"))); + const foreign = tempDir(); + fs.writeFileSync(path.join(foreign, "notes.txt"), "mine"); + const r = await merge(a, b, foreign); + assert.equal(r.code, 2); + assert.match(r.stderr, /refusing to wipe/); + assert.equal(fs.readFileSync(path.join(foreign, "notes.txt"), "utf8"), "mine"); + }); + + test("refuses two kept shots writing one file before touching --out", async () => { + const clash = shot("/A", { images: imgs("a.1440") }); + const out = path.join(tempDir(), "o"); + const r = await merge(full(), partial([clash]), out); + assert.equal(r.code, 2); + assert.match(r.stderr, /\/a@1440 and \/A@1440 both write a\.1440\.left\.png/); + assert.equal(fs.existsSync(out), false); + }); +});