From 3fb0c7b5962c3dc9bf0a5d41d5a9d6e78fd99c05 Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Thu, 2 Jul 2026 19:37:49 +0000 Subject: [PATCH 1/3] feat(snapshots): add `snapshots diff` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ports `sentry snapshots diff` — compares two local directories of snapshot images. Uses pure-JS pixelmatch (the same YIQ, anti-aliasing-aware algorithm as the legacy CLI's native odiff) + pngjs/jpeg-js for decoding — no native/WASM deps, bundles cleanly into the SEA binary. Collects images recursively (png/jpg/jpeg), categorizes matched/added/removed (or skipped with --selective), byte-identical pairs short-circuit, then diffs matched pairs: dimension mismatch → layout_changed, differing pixels → changed with a PNG diff mask written to --output. Emits a JSON report + summary; --fail-on-diff exits non-zero on any change. --threshold (0-1) and --no-antialiasing tune the comparison. - src/lib/snapshots/diff.ts: compareImages, collectImageFiles (shared walkFiles), categorizeImages. - src/commands/snapshots/diff.ts + route registration. - devDeps: pixelmatch, pngjs, jpeg-js, @types/pngjs (all bundled). - Tests: compare (match/changed/layout), categorize (+selective), collect; command (mask write, fail-on-diff exit, missing-dir rejection). --- docs/src/content/docs/contributing.md | 2 +- docs/src/fragments/commands/snapshots.md | 11 + package.json | 4 + plugins/sentry-cli/skills/sentry-cli/SKILL.md | 1 + .../skills/sentry-cli/references/snapshots.md | 17 + pnpm-lock.yaml | 33 ++ src/commands/snapshots/diff.ts | 357 ++++++++++++++++++ src/commands/snapshots/index.ts | 4 +- src/lib/snapshots/diff.ts | 164 ++++++++ test/commands/snapshots/diff.test.ts | 125 ++++++ test/lib/snapshots/diff.test.ts | 117 ++++++ 11 files changed, 833 insertions(+), 2 deletions(-) create mode 100644 src/commands/snapshots/diff.ts create mode 100644 src/lib/snapshots/diff.ts create mode 100644 test/commands/snapshots/diff.test.ts create mode 100644 test/lib/snapshots/diff.test.ts diff --git a/docs/src/content/docs/contributing.md b/docs/src/content/docs/contributing.md index e83b168ec1..2bf3adbe89 100644 --- a/docs/src/content/docs/contributing.md +++ b/docs/src/content/docs/contributing.md @@ -71,7 +71,7 @@ cli/ │ │ ├── release/ # archive, create, delete, deploy, deploys, finalize, list, propose-version, restore, set-commits, view │ │ ├── replay/ # list, view │ │ ├── repo/ # list -│ │ ├── snapshots/ # download +│ │ ├── snapshots/ # diff, download │ │ ├── sourcemap/ # inject, resolve, upload │ │ ├── span/ # list, view │ │ ├── team/ # list diff --git a/docs/src/fragments/commands/snapshots.md b/docs/src/fragments/commands/snapshots.md index 3e7a8be6cc..d4d8dc4eed 100644 --- a/docs/src/fragments/commands/snapshots.md +++ b/docs/src/fragments/commands/snapshots.md @@ -3,6 +3,12 @@ ## Examples ```bash +# Compare two directories of snapshot images locally +sentry snapshots diff ./baseline ./head + +# Fail (non-zero exit) if any images changed, with a custom threshold +sentry snapshots diff ./baseline ./head --fail-on-diff --threshold 0.02 + # Download a specific baseline snapshot by ID sentry snapshots download --snapshot-id 1234567890 @@ -15,6 +21,11 @@ sentry snapshots download --app-id my-app --output ./baseline/ ## Important Notes +- `snapshots diff` compares two local image directories (PNG/JPEG) perceptually + — anti-aliasing aware, with a per-pixel `--threshold` (0.0–1.0) — and writes a + PNG diff mask per changed image. It makes **no network requests**. Use + `--fail-on-diff` to exit non-zero when any images changed/added/removed, and + `--selective` to treat images missing from head as skipped rather than removed. - `snapshots download` fetches baseline snapshot images from Sentry's preprod system and extracts them to a local directory. **Sentry SaaS only.** - Provide exactly one of `--snapshot-id` (a direct artifact ID) or `--app-id` diff --git a/package.json b/package.json index b0f7983d46..a9a1ed4e8a 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "@types/http-cache-semantics": "^4.2.0", "@types/node": "^22.20.0", "@types/picomatch": "^4.0.3", + "@types/pngjs": "^6.0.5", "@types/qrcode-terminal": "^0.12.2", "@types/react": "^19.2.17", "@types/semver": "^7.7.1", @@ -39,10 +40,13 @@ "ignore": "^7.0.5", "ink": "^7.1.0", "ink-spinner": "^5.0.0", + "jpeg-js": "^0.4.4", "marked": "^15.0.12", "p-limit": "^7.3.0", "peggy": "^5.1.0", "picomatch": "^4.0.4", + "pixelmatch": "^7.2.0", + "pngjs": "^7.0.0", "pretty-ms": "^9.3.0", "qrcode-terminal": "^0.12.0", "react": "^19.2.7", diff --git a/plugins/sentry-cli/skills/sentry-cli/SKILL.md b/plugins/sentry-cli/skills/sentry-cli/SKILL.md index a183b8f547..355136aaa1 100644 --- a/plugins/sentry-cli/skills/sentry-cli/SKILL.md +++ b/plugins/sentry-cli/skills/sentry-cli/SKILL.md @@ -524,6 +524,7 @@ Work with Sentry cron monitors Manage and compare snapshots +- `sentry snapshots diff ` — Compare two directories of snapshot images - `sentry snapshots download` — Download baseline snapshot images → Full flags and examples: `references/snapshots.md` diff --git a/plugins/sentry-cli/skills/sentry-cli/references/snapshots.md b/plugins/sentry-cli/skills/sentry-cli/references/snapshots.md index 70ff99515b..566edc0b3a 100644 --- a/plugins/sentry-cli/skills/sentry-cli/references/snapshots.md +++ b/plugins/sentry-cli/skills/sentry-cli/references/snapshots.md @@ -11,6 +11,17 @@ requires: Manage and compare snapshots +### `sentry snapshots diff ` + +Compare two directories of snapshot images + +**Flags:** +- `-o, --output - Directory for diff mask images (default: ./diff-output/)` +- `--threshold - Pixel color difference threshold (0.0-1.0) - (default: "0.01")` +- `--no-antialiasing - Disable antialiasing detection` +- `--fail-on-diff - Exit non-zero if any diffs (changed/added/removed/errored) are found` +- `--selective - Treat images missing from head as skipped instead of removed` + ### `sentry snapshots download` Download baseline snapshot images @@ -24,6 +35,12 @@ Download baseline snapshot images **Examples:** ```bash +# Compare two directories of snapshot images locally +sentry snapshots diff ./baseline ./head + +# Fail (non-zero exit) if any images changed, with a custom threshold +sentry snapshots diff ./baseline ./head --fail-on-diff --threshold 0.02 + # Download a specific baseline snapshot by ID sentry snapshots download --snapshot-id 1234567890 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 30fd34e641..085b61435f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -74,6 +74,9 @@ importers: '@types/picomatch': specifier: ^4.0.3 version: 4.0.3 + '@types/pngjs': + specifier: ^6.0.5 + version: 6.0.5 '@types/qrcode-terminal': specifier: ^0.12.2 version: 0.12.2 @@ -122,6 +125,9 @@ importers: ink-spinner: specifier: ^5.0.0 version: 5.0.0(ink@7.1.0(@types/react@19.2.17)(react-devtools-core@7.0.1)(react@19.2.7))(react@19.2.7) + jpeg-js: + specifier: ^0.4.4 + version: 0.4.4 marked: specifier: ^15.0.12 version: 15.0.12 @@ -134,6 +140,12 @@ importers: picomatch: specifier: ^4.0.4 version: 4.0.4 + pixelmatch: + specifier: ^7.2.0 + version: 7.2.0 + pngjs: + specifier: ^7.0.0 + version: 7.0.0 pretty-ms: specifier: ^9.3.0 version: 9.3.0 @@ -880,6 +892,9 @@ packages: '@types/picomatch@4.0.3': resolution: {integrity: sha512-iG0T6+nYJ9FAPmx9SsUlnwcq1ZVRuCXcVEvWnntoPlrOpwtSTKNDC9uVAxTsC3PUvJ+99n4RpAcNgBbHX3JSnQ==} + '@types/pngjs@6.0.5': + resolution: {integrity: sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==} + '@types/qrcode-terminal@0.12.2': resolution: {integrity: sha512-v+RcIEJ+Uhd6ygSQ0u5YYY7ZM+la7GgPbs0V/7l/kFs2uO4S8BcIUEMoP7za4DNIqNnUD5npf0A/7kBhrCKG5Q==} @@ -2082,10 +2097,18 @@ packages: resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} engines: {node: '>=12'} + pixelmatch@7.2.0: + resolution: {integrity: sha512-xhcb4yHu9sM/G7foGzoLtXYcC0zHEaOXXjRKhGup0fw78Nf2Tkiapv4EQyMzrbcmQPsllAI7DbFY2UT7PlI9Pg==} + hasBin: true + pkce-challenge@5.0.1: resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} engines: {node: '>=16.20.0'} + pngjs@7.0.0: + resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==} + engines: {node: '>=14.19.0'} + portable-executable-signature@2.0.6: resolution: {integrity: sha512-VV+1GuJca0cJ0PFwnCW/xK8Ro9DDX38e4iUDh6ngPjd9vj7VLiemh9rSlqquvcVGtClkVzYaV/UseMVnUrxS/Q==} engines: {node: '>=18.12.0'} @@ -3368,6 +3391,10 @@ snapshots: '@types/picomatch@4.0.3': {} + '@types/pngjs@6.0.5': + dependencies: + '@types/node': 22.20.0 + '@types/qrcode-terminal@0.12.2': {} '@types/react@19.2.17': @@ -4667,8 +4694,14 @@ snapshots: picomatch@4.0.4: {} + pixelmatch@7.2.0: + dependencies: + pngjs: 7.0.0 + pkce-challenge@5.0.1: {} + pngjs@7.0.0: {} + portable-executable-signature@2.0.6: {} postcss@8.5.15: diff --git a/src/commands/snapshots/diff.ts b/src/commands/snapshots/diff.ts new file mode 100644 index 0000000000..848e4011eb --- /dev/null +++ b/src/commands/snapshots/diff.ts @@ -0,0 +1,357 @@ +/** + * sentry snapshots diff + * + * Compare two directories of snapshot images locally. Images present in both + * are diffed perceptually (pure-JS pixelmatch, equivalent to the legacy CLI's + * odiff); byte-identical pairs short-circuit. Emits a JSON report and writes a + * PNG diff mask per changed image. + * + * Local-only — no API calls. + */ + +import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { basename, dirname, extname, join, resolve } from "node:path"; +import type { SentryContext } from "../../context.js"; +import { buildCommand } from "../../lib/command.js"; +import { ValidationError } from "../../lib/errors.js"; +import { + colorTag, + mdKvTable, + renderMarkdown, +} from "../../lib/formatters/markdown.js"; +import { CommandOutput } from "../../lib/formatters/output.js"; +import { + categorizeImages, + collectImageFiles, + compareImages, + type DiffOptions, +} from "../../lib/snapshots/diff.js"; + +const DEFAULT_OUTPUT = "./diff-output/"; + +/** Per-image comparison status. */ +type ImageStatus = + | "unchanged" + | "changed" + | "layout_changed" + | "added" + | "removed" + | "skipped" + | "error"; + +/** Result for a single image. */ +type ImageResult = { + name: string; + status: ImageStatus; + diffPercentage?: number; + diffPixelCount?: number; + diffMaskPath?: string; + error?: string; +}; + +/** Aggregate counts across all images. */ +type DiffSummary = { + total: number; + changed: number; + unchanged: number; + added: number; + removed: number; + skipped: number; + errored: number; +}; + +/** Structured result for `snapshots diff`. */ +type DiffReport = { + baseDir: string; + headDir: string; + outputDir: string; + threshold: number; + summary: DiffSummary; + images: ImageResult[]; +}; + +/** Flags accepted by `snapshots diff`. */ +type DiffFlags = { + output?: string; + threshold?: number; + "no-antialiasing"?: boolean; + "fail-on-diff"?: boolean; + selective?: boolean; +}; + +/** Parse `--threshold` as a float in [0, 1]. */ +function parseThreshold(value: string): number { + const parsed = Number(value); + if (Number.isNaN(parsed) || parsed < 0 || parsed > 1) { + throw new Error("threshold must be a number between 0.0 and 1.0"); + } + return parsed; +} + +/** Extract a message from a thrown value. */ +function errorMessage(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} + +/** Assert a path is an existing directory. */ +function assertDirectory(path: string, label: string): void { + try { + if (statSync(path).isDirectory()) { + return; + } + } catch { + // Fall through to the error below. + } + throw new ValidationError( + `${label} directory does not exist: ${path}`, + "dir" + ); +} + +/** The diff mask path for an image, with a `.png` extension. */ +function diffMaskRelPath(rel: string): string { + const stem = basename(rel, extname(rel)); + const dir = dirname(rel); + return dir === "." ? `${stem}.png` : join(dir, `${stem}.png`); +} + +/** The base/head/output directories for a diff run. */ +type DiffDirs = { baseDir: string; headDir: string; outputDir: string }; + +/** Compare a single matched image, writing its diff mask when changed. */ +function compareMatched( + dirs: DiffDirs, + rel: string, + opts: DiffOptions +): ImageResult { + let baseBuf: Buffer; + let headBuf: Buffer; + try { + baseBuf = readFileSync(join(dirs.baseDir, rel)); + headBuf = readFileSync(join(dirs.headDir, rel)); + } catch (err) { + return { name: rel, status: "error", error: errorMessage(err) }; + } + + // Fast path: byte-identical files can't differ visually. + if (baseBuf.equals(headBuf)) { + return { name: rel, status: "unchanged" }; + } + + let result: ReturnType; + try { + result = compareImages(baseBuf, headBuf, rel, opts); + } catch (err) { + return { name: rel, status: "error", error: errorMessage(err) }; + } + + if (result.kind === "match") { + return { name: rel, status: "unchanged" }; + } + if (result.kind === "layout") { + return { name: rel, status: "layout_changed" }; + } + + const maskPath = join(dirs.outputDir, diffMaskRelPath(rel)); + try { + mkdirSync(dirname(maskPath), { recursive: true }); + writeFileSync(maskPath, result.mask); + } catch (err) { + return { name: rel, status: "error", error: errorMessage(err) }; + } + return { + name: rel, + status: "changed", + diffPercentage: result.diffPercentage, + diffPixelCount: result.diffCount, + diffMaskPath: maskPath, + }; +} + +/** Build the aggregate summary from per-image results. */ +function summarize(images: ImageResult[]): DiffSummary { + const count = (...statuses: ImageStatus[]) => + images.filter((img) => statuses.includes(img.status)).length; + return { + total: images.length, + changed: count("changed", "layout_changed"), + unchanged: count("unchanged"), + added: count("added"), + removed: count("removed"), + skipped: count("skipped"), + errored: count("error"), + }; +} + +/** Short per-image detail for the human summary (diff %, error, or blank). */ +function notableDetail(img: ImageResult): string { + if (img.status === "changed" && img.diffPercentage !== undefined) { + return `${(img.diffPercentage * 100).toFixed(2)}%`; + } + if (img.error) { + return colorTag("error", img.error); + } + return ""; +} + +/** Human-readable formatter: a summary table plus notable per-image rows. */ +function formatDiffReport(data: DiffReport): string { + const { summary } = data; + const table = mdKvTable([ + ["Total", String(summary.total)], + ["Changed", String(summary.changed)], + ["Unchanged", String(summary.unchanged)], + ["Added", String(summary.added)], + ["Removed", String(summary.removed)], + ["Skipped", String(summary.skipped)], + ["Errored", String(summary.errored)], + ]); + + const notable = data.images.filter((img) => img.status !== "unchanged"); + if (notable.length === 0) { + return renderMarkdown(table); + } + const rows = notable.map((img): [string, string] => [ + img.name, + `${img.status} ${notableDetail(img)}`.trim(), + ]); + return renderMarkdown(`${table}\n\n${mdKvTable(rows)}`); +} + +export const diffCommand = buildCommand({ + // Local-only: reads two image directories, no network access. + auth: false, + docs: { + brief: "Compare two directories of snapshot images", + fullDescription: + "Compare two directories of snapshot images locally. Images present in " + + "both directories are diffed perceptually; a PNG diff mask is written " + + "for each changed image, and a JSON report is printed.\n\n" + + "Comparison is anti-aliasing aware (disable with --no-antialiasing) and " + + "makes no network requests.\n\n" + + "Usage:\n" + + " sentry snapshots diff ./baseline ./head\n" + + " sentry snapshots diff ./baseline ./head --threshold 0.02 --output ./diffs/\n" + + " sentry snapshots diff ./baseline ./head --fail-on-diff", + }, + output: { + human: formatDiffReport, + }, + parameters: { + positional: { + kind: "tuple", + parameters: [ + { + brief: "Path to the baseline image directory", + parse: String, + placeholder: "base-dir", + }, + { + brief: "Path to the head image directory", + parse: String, + placeholder: "head-dir", + }, + ], + }, + flags: { + output: { + kind: "parsed", + parse: String, + brief: `Directory for diff mask images (default: ${DEFAULT_OUTPUT})`, + optional: true, + }, + threshold: { + kind: "parsed", + parse: parseThreshold, + brief: "Pixel color difference threshold (0.0-1.0)", + default: "0.01", + }, + "no-antialiasing": { + kind: "boolean", + brief: "Disable antialiasing detection", + optional: true, + }, + "fail-on-diff": { + kind: "boolean", + brief: + "Exit non-zero if any diffs (changed/added/removed/errored) are found", + optional: true, + }, + selective: { + kind: "boolean", + brief: "Treat images missing from head as skipped instead of removed", + optional: true, + }, + }, + aliases: { + o: "output", + }, + }, + async *func( + this: SentryContext, + flags: DiffFlags, + baseDirArg: string, + headDirArg: string + ) { + const baseDir = resolve(this.cwd, baseDirArg); + const headDir = resolve(this.cwd, headDirArg); + assertDirectory(baseDir, "Base"); + assertDirectory(headDir, "Head"); + + const outputDir = resolve(this.cwd, flags.output ?? DEFAULT_OUTPUT); + const opts: DiffOptions = { + threshold: flags.threshold ?? 0.01, + antialiasing: !flags["no-antialiasing"], + }; + + const [baseFiles, headFiles] = await Promise.all([ + collectImageFiles(baseDir), + collectImageFiles(headDir), + ]); + const categorized = categorizeImages( + baseFiles, + headFiles, + Boolean(flags.selective) + ); + + const dirs: DiffDirs = { baseDir, headDir, outputDir }; + const images: ImageResult[] = []; + for (const rel of categorized.matched) { + images.push(compareMatched(dirs, rel, opts)); + } + for (const rel of categorized.added) { + images.push({ name: rel, status: "added" }); + } + for (const rel of categorized.removed) { + images.push({ name: rel, status: "removed" }); + } + for (const rel of categorized.skipped) { + images.push({ name: rel, status: "skipped" }); + } + + const summary = summarize(images); + yield new CommandOutput({ + baseDir, + headDir, + outputDir, + threshold: opts.threshold, + summary, + images, + }); + + const failures = + summary.changed + summary.added + summary.removed + summary.errored; + if (flags["fail-on-diff"] && failures > 0) { + this.process.exitCode = 1; + return { + hint: `${failures} image(s) differed from baseline; diff masks written to ${outputDir}`, + }; + } + return { + hint: + summary.changed > 0 + ? `Diff masks written to ${outputDir}` + : "No changes detected.", + }; + }, +}); diff --git a/src/commands/snapshots/index.ts b/src/commands/snapshots/index.ts index f81fe217f0..bdf94b5fef 100644 --- a/src/commands/snapshots/index.ts +++ b/src/commands/snapshots/index.ts @@ -1,14 +1,16 @@ /** * `sentry snapshots` — manage and compare preprod snapshot images. * - * Currently exposes `download`. `diff` and `upload` are ported separately. + * Exposes `download` and `diff`. `upload` is ported separately (objectstore). */ import { buildRouteMap } from "../../lib/route-map.js"; +import { diffCommand } from "./diff.js"; import { downloadCommand } from "./download.js"; export const snapshotsRoute = buildRouteMap({ routes: { + diff: diffCommand, download: downloadCommand, }, docs: { diff --git a/src/lib/snapshots/diff.ts b/src/lib/snapshots/diff.ts new file mode 100644 index 0000000000..bc3ccac06d --- /dev/null +++ b/src/lib/snapshots/diff.ts @@ -0,0 +1,164 @@ +/** + * Local snapshot image diffing. + * + * Pure-JS perceptual image comparison (no native/WASM deps): `pixelmatch` + * implements the same YIQ-color-space, anti-aliasing-aware algorithm as the + * legacy CLI's `odiff`, and `pngjs`/`jpeg-js` decode the inputs. The diff mask + * is always written as PNG. + */ + +import { extname, resolve } from "node:path"; +import { decode as decodeJpeg } from "jpeg-js"; +import pixelmatch from "pixelmatch"; +import { PNG } from "pngjs"; +import { ValidationError } from "../errors.js"; +import { walkFiles } from "../scan/walker.js"; + +/** Image file extensions eligible for diffing (matches the legacy CLI). */ +export const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg"] as const; + +/** Extension allowlist for {@link walkFiles} (extname form, with the dot). */ +const IMAGE_EXT_SET: ReadonlySet = new Set( + IMAGE_EXTENSIONS.map((ext) => `.${ext}`) +); + +/** + * Recursively collect image files under a directory. + * + * @param dir - Directory to walk. + * @returns POSIX-normalized paths relative to `dir`, sorted. + */ +export async function collectImageFiles(dir: string): Promise { + const relativePaths: string[] = []; + for await (const entry of walkFiles({ + cwd: resolve(dir), + extensions: IMAGE_EXT_SET, + respectGitignore: false, + alwaysSkipDirs: [], + maxFileSize: Number.POSITIVE_INFINITY, + followSymlinks: true, + classifyBinary: false, + })) { + relativePaths.push(entry.relativePath); + } + return relativePaths.sort(); +} + +/** Image files partitioned by presence in the base vs head directories. */ +export type CategorizedImages = { + /** Present in both directories. */ + matched: string[]; + /** Present only in head. */ + added: string[]; + /** Present only in base (empty when `selective`). */ + removed: string[]; + /** Base-only images treated as skipped instead of removed (`selective`). */ + skipped: string[]; +}; + +/** + * Partition base/head image paths into matched/added/removed/skipped. + * + * @param selective - When true, base-only images are `skipped` (not `removed`), + * so missing head images aren't reported as removals. + */ +export function categorizeImages( + base: string[], + head: string[], + selective: boolean +): CategorizedImages { + const baseSet = new Set(base); + const headSet = new Set(head); + const matched = base.filter((p) => headSet.has(p)); + const added = head.filter((p) => !baseSet.has(p)); + const baseOnly = base.filter((p) => !headSet.has(p)); + return selective + ? { matched, added, removed: [], skipped: baseOnly } + : { matched, added, removed: baseOnly, skipped: [] }; +} + +/** A decoded image as raw RGBA pixels. */ +type DecodedImage = { width: number; height: number; data: Uint8Array }; + +/** Options controlling a single image comparison. */ +export type DiffOptions = { + /** Per-pixel color-difference sensitivity (0..1); matches odiff's threshold. */ + threshold: number; + /** When true, anti-aliased pixels are NOT counted as differences. */ + antialiasing: boolean; +}; + +/** + * Result of comparing two images: + * - `match`: pixel-identical within the threshold. + * - `layout`: dimensions differ (no per-pixel diff possible). + * - `changed`: differing pixels, with a PNG diff mask. + */ +export type ImageDiff = + | { kind: "match" } + | { kind: "layout" } + | { + kind: "changed"; + diffCount: number; + diffPercentage: number; + mask: Buffer; + }; + +/** Decode PNG/JPEG bytes to RGBA. */ +function decodeImage(buffer: Buffer, path: string): DecodedImage { + const ext = extname(path).slice(1).toLowerCase(); + if (ext === "png") { + const png = PNG.sync.read(buffer); + return { width: png.width, height: png.height, data: png.data }; + } + if (ext === "jpg" || ext === "jpeg") { + const jpg = decodeJpeg(buffer, { useTArray: true, formatAsRGBA: true }); + return { width: jpg.width, height: jpg.height, data: jpg.data }; + } + throw new ValidationError(`Unsupported image format: ${path}`, "image"); +} + +/** + * Compare two already-read image buffers. + * + * @param baseBuf - Baseline image bytes. + * @param headBuf - Head image bytes. + * @param path - Relative path (used for extension detection + errors). + * @param opts - Threshold / antialiasing options. + * @throws {ValidationError} On an unsupported format. + * @throws On undecodable image data (surfaced by the caller as an error entry). + */ +export function compareImages( + baseBuf: Buffer, + headBuf: Buffer, + path: string, + opts: DiffOptions +): ImageDiff { + const base = decodeImage(baseBuf, path); + const head = decodeImage(headBuf, path); + + if (base.width !== head.width || base.height !== head.height) { + return { kind: "layout" }; + } + + const { width, height } = base; + const output = Buffer.alloc(width * height * 4); + const diffCount = pixelmatch(base.data, head.data, output, width, height, { + threshold: opts.threshold, + includeAA: !opts.antialiasing, + diffMask: true, + }); + + if (diffCount === 0) { + return { kind: "match" }; + } + + const png = new PNG({ width, height }); + png.data = output; + return { + kind: "changed", + diffCount, + diffPercentage: diffCount / (width * height), + mask: PNG.sync.write(png), + }; +} diff --git a/test/commands/snapshots/diff.test.ts b/test/commands/snapshots/diff.test.ts new file mode 100644 index 0000000000..0efa9aee2a --- /dev/null +++ b/test/commands/snapshots/diff.test.ts @@ -0,0 +1,125 @@ +/** + * Tests for `sentry snapshots diff`. + * + * Drives the command via its wrapper `loader()` against real image + * directories generated with pngjs. Asserts side effects (mask files, exit + * code) rather than the rendered markdown. + */ + +import { + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { PNG } from "pngjs"; +import { afterEach, beforeEach, describe, expect, test } from "vitest"; +import { diffCommand } from "../../../src/commands/snapshots/diff.js"; +import { ValidationError } from "../../../src/lib/errors.js"; + +let tmpDir: string; +let baseDir: string; +let headDir: string; +let outDir: string; + +function png(rgb: [number, number, number]): Buffer { + const image = new PNG({ width: 4, height: 4 }); + for (let i = 0; i < 4 * 4 * 4; i += 4) { + image.data[i] = rgb[0]; + image.data[i + 1] = rgb[1]; + image.data[i + 2] = rgb[2]; + image.data[i + 3] = 255; + } + return PNG.sync.write(image); +} + +function createContext() { + return { + context: { + stdout: { write: () => true }, + stderr: { write: () => true }, + cwd: tmpDir, + env: {} as NodeJS.ProcessEnv, + process: { ...process, exitCode: undefined } as typeof process, + }, + get exitCode() { + return this.context.process.exitCode; + }, + }; +} + +describe("snapshots diff", () => { + beforeEach(() => { + tmpDir = mkdtempSync(join(tmpdir(), "snap-diff-cmd-")); + baseDir = join(tmpDir, "base"); + headDir = join(tmpDir, "head"); + outDir = join(tmpDir, "out"); + mkdirSync(baseDir); + mkdirSync(headDir); + }); + + afterEach(() => { + rmSync(tmpDir, { recursive: true, force: true }); + }); + + test("writes a diff mask for changed images and reports status", async () => { + writeFileSync(join(baseDir, "changed.png"), png([255, 0, 0])); + writeFileSync(join(headDir, "changed.png"), png([0, 255, 0])); + writeFileSync(join(baseDir, "same.png"), png([9, 9, 9])); + writeFileSync(join(headDir, "same.png"), png([9, 9, 9])); + writeFileSync(join(headDir, "added.png"), png([1, 1, 1])); + + const harness = createContext(); + const func = await diffCommand.loader(); + await func.call(harness.context, { output: outDir }, baseDir, headDir); + + // A mask was written for the changed image, but not the unchanged one. + expect(existsSync(join(outDir, "changed.png"))).toBe(true); + expect(existsSync(join(outDir, "same.png"))).toBe(false); + // Without --fail-on-diff, a clean (zero) exit even with changes. + expect(harness.exitCode ?? 0).toBe(0); + }); + + test("--fail-on-diff exits non-zero when changes exist", async () => { + writeFileSync(join(baseDir, "a.png"), png([0, 0, 0])); + writeFileSync(join(headDir, "a.png"), png([255, 255, 255])); + + const harness = createContext(); + const func = await diffCommand.loader(); + await func.call( + harness.context, + { output: outDir, "fail-on-diff": true }, + baseDir, + headDir + ); + + expect(harness.exitCode).toBe(1); + }); + + test("--fail-on-diff exits cleanly when there are no changes", async () => { + writeFileSync(join(baseDir, "a.png"), png([5, 5, 5])); + writeFileSync(join(headDir, "a.png"), png([5, 5, 5])); + + const harness = createContext(); + const func = await diffCommand.loader(); + await func.call( + harness.context, + { output: outDir, "fail-on-diff": true }, + baseDir, + headDir + ); + + expect(harness.exitCode ?? 0).toBe(0); + }); + + test("rejects a missing base directory", async () => { + const harness = createContext(); + const func = await diffCommand.loader(); + await expect( + func.call(harness.context, {}, join(tmpDir, "nope"), headDir) + ).rejects.toThrow(ValidationError); + }); +}); diff --git a/test/lib/snapshots/diff.test.ts b/test/lib/snapshots/diff.test.ts new file mode 100644 index 0000000000..9208f3aac8 --- /dev/null +++ b/test/lib/snapshots/diff.test.ts @@ -0,0 +1,117 @@ +/** + * Tests for local snapshot image diffing (pixelmatch + pngjs). + * + * Fixtures are generated in-memory with pngjs — no committed binaries. + */ + +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { PNG } from "pngjs"; +import { afterEach, describe, expect, test } from "vitest"; +import { + categorizeImages, + collectImageFiles, + compareImages, +} from "../../../src/lib/snapshots/diff.js"; + +/** Build a solid-color PNG of the given size. */ +function png( + width: number, + height: number, + rgb: [number, number, number] +): Buffer { + const image = new PNG({ width, height }); + for (let i = 0; i < width * height * 4; i += 4) { + image.data[i] = rgb[0]; + image.data[i + 1] = rgb[1]; + image.data[i + 2] = rgb[2]; + image.data[i + 3] = 255; + } + return PNG.sync.write(image); +} + +const OPTS = { threshold: 0.1, antialiasing: true }; + +describe("compareImages", () => { + test("identical pixels → match", () => { + const result = compareImages( + png(4, 4, [10, 20, 30]), + png(4, 4, [10, 20, 30]), + "a.png", + OPTS + ); + expect(result.kind).toBe("match"); + }); + + test("differing pixels → changed with a mask", () => { + const result = compareImages( + png(4, 4, [255, 0, 0]), + png(4, 4, [0, 255, 0]), + "a.png", + OPTS + ); + expect(result.kind).toBe("changed"); + if (result.kind === "changed") { + expect(result.diffCount).toBe(16); + expect(result.diffPercentage).toBe(1); + expect(result.mask.length).toBeGreaterThan(0); + } + }); + + test("mismatched dimensions → layout", () => { + const result = compareImages( + png(4, 4, [0, 0, 0]), + png(8, 8, [0, 0, 0]), + "a.png", + OPTS + ); + expect(result.kind).toBe("layout"); + }); +}); + +describe("categorizeImages", () => { + test("partitions matched/added/removed", () => { + expect(categorizeImages(["a", "b"], ["b", "c"], false)).toEqual({ + matched: ["b"], + added: ["c"], + removed: ["a"], + skipped: [], + }); + }); + + test("selective treats base-only images as skipped", () => { + expect(categorizeImages(["a", "b"], ["b", "c"], true)).toEqual({ + matched: ["b"], + added: ["c"], + removed: [], + skipped: ["a"], + }); + }); +}); + +describe("collectImageFiles", () => { + const dirs: string[] = []; + afterEach(() => { + while (dirs.length > 0) { + const dir = dirs.pop(); + if (dir) { + rmSync(dir, { recursive: true, force: true }); + } + } + }); + + test("collects images recursively and skips non-images", async () => { + const dir = mkdtempSync(join(tmpdir(), "snap-collect-")); + dirs.push(dir); + writeFileSync(join(dir, "a.png"), png(2, 2, [0, 0, 0])); + mkdirSync(join(dir, "sub")); + writeFileSync(join(dir, "sub", "b.png"), png(2, 2, [0, 0, 0])); + writeFileSync(join(dir, "notes.txt"), "not an image"); + + await expect(collectImageFiles(dir)).resolves.toEqual([ + "a.png", + "sub/b.png", + ]); + }); +}); From 13f2e9aad416331a11c7727c2f74cd6114fcedbf Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Thu, 2 Jul 2026 19:54:16 +0000 Subject: [PATCH 2/3] fix(snapshots): self-review fixes for diff MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - H1 (parity): emit diffPercentage as a percentage (0–100), matching legacy odiff output — was a fraction (0–1), 100× off for JSON/threshold consumers. Drop the compensating *100 in the human formatter; update the test. - L1: colorTag("red", ...) for error detail ("error" is not a valid tag). - Tests: add JPEG decode, undecodable-image (lib throw + command error entry), added/removed reporting, --selective (skipped vs removed via exit code), and --no-antialiasing coverage. --- src/commands/snapshots/diff.ts | 5 +- src/lib/snapshots/diff.ts | 4 +- test/commands/snapshots/diff.test.ts | 86 +++++++++++++++++++++++++++- test/lib/snapshots/diff.test.ts | 41 ++++++++++++- 4 files changed, 131 insertions(+), 5 deletions(-) diff --git a/src/commands/snapshots/diff.ts b/src/commands/snapshots/diff.ts index 848e4011eb..872e93a041 100644 --- a/src/commands/snapshots/diff.ts +++ b/src/commands/snapshots/diff.ts @@ -43,6 +43,7 @@ type ImageStatus = type ImageResult = { name: string; status: ImageStatus; + /** Percentage of differing pixels (0–100); set only for `changed`. */ diffPercentage?: number; diffPixelCount?: number; diffMaskPath?: string; @@ -186,10 +187,10 @@ function summarize(images: ImageResult[]): DiffSummary { /** Short per-image detail for the human summary (diff %, error, or blank). */ function notableDetail(img: ImageResult): string { if (img.status === "changed" && img.diffPercentage !== undefined) { - return `${(img.diffPercentage * 100).toFixed(2)}%`; + return `${img.diffPercentage.toFixed(2)}%`; } if (img.error) { - return colorTag("error", img.error); + return colorTag("red", img.error); } return ""; } diff --git a/src/lib/snapshots/diff.ts b/src/lib/snapshots/diff.ts index bc3ccac06d..ab022a3577 100644 --- a/src/lib/snapshots/diff.ts +++ b/src/lib/snapshots/diff.ts @@ -99,7 +99,9 @@ export type ImageDiff = | { kind: "layout" } | { kind: "changed"; + /** Number of differing pixels. */ diffCount: number; + /** Percentage of differing pixels (0–100), matching the legacy odiff output. */ diffPercentage: number; mask: Buffer; }; @@ -158,7 +160,7 @@ export function compareImages( return { kind: "changed", diffCount, - diffPercentage: diffCount / (width * height), + diffPercentage: (diffCount / (width * height)) * 100, mask: PNG.sync.write(png), }; } diff --git a/test/commands/snapshots/diff.test.ts b/test/commands/snapshots/diff.test.ts index 0efa9aee2a..ae109ca87c 100644 --- a/test/commands/snapshots/diff.test.ts +++ b/test/commands/snapshots/diff.test.ts @@ -37,14 +37,23 @@ function png(rgb: [number, number, number]): Buffer { } function createContext() { + const writes: string[] = []; return { context: { - stdout: { write: () => true }, + stdout: { + write: (data: string | Uint8Array) => { + writes.push( + typeof data === "string" ? data : new TextDecoder().decode(data) + ); + return true; + }, + }, stderr: { write: () => true }, cwd: tmpDir, env: {} as NodeJS.ProcessEnv, process: { ...process, exitCode: undefined } as typeof process, }, + output: () => writes.join(""), get exitCode() { return this.context.process.exitCode; }, @@ -115,6 +124,81 @@ describe("snapshots diff", () => { expect(harness.exitCode ?? 0).toBe(0); }); + test("reports added and removed images", async () => { + writeFileSync(join(baseDir, "shared.png"), png([7, 7, 7])); + writeFileSync(join(headDir, "shared.png"), png([7, 7, 7])); + writeFileSync(join(baseDir, "gone.png"), png([1, 2, 3])); + writeFileSync(join(headDir, "new.png"), png([4, 5, 6])); + + const harness = createContext(); + const func = await diffCommand.loader(); + await func.call(harness.context, { output: outDir }, baseDir, headDir); + + const out = harness.output(); + expect(out).toContain("new.png"); + expect(out).toContain("gone.png"); + }); + + test("--selective treats base-only images as skipped (no failure)", async () => { + writeFileSync(join(baseDir, "only-in-base.png"), png([1, 1, 1])); + + // Without --selective, a base-only image is a removal → fail-on-diff exits 1. + const removedHarness = createContext(); + const func = await diffCommand.loader(); + await func.call( + removedHarness.context, + { output: outDir, "fail-on-diff": true }, + baseDir, + headDir + ); + expect(removedHarness.exitCode).toBe(1); + + // With --selective, it's skipped instead → clean exit. + const skippedHarness = createContext(); + await func.call( + skippedHarness.context, + { output: outDir, "fail-on-diff": true, selective: true }, + baseDir, + headDir + ); + expect(skippedHarness.exitCode ?? 0).toBe(0); + }); + + test("records an error entry for an undecodable image without aborting", async () => { + // Differing (so not byte-identical) but undecodable bytes. + writeFileSync(join(baseDir, "bad.png"), Buffer.from("not a png AAAA")); + writeFileSync(join(headDir, "bad.png"), Buffer.from("not a png BBBB")); + + const harness = createContext(); + const func = await diffCommand.loader(); + await func.call( + harness.context, + { output: outDir, "fail-on-diff": true }, + baseDir, + headDir + ); + + // Errored images count toward --fail-on-diff, and the run still completes. + expect(harness.exitCode).toBe(1); + expect(harness.output()).toContain("bad.png"); + }); + + test("--no-antialiasing runs and still writes masks", async () => { + writeFileSync(join(baseDir, "a.png"), png([0, 0, 0])); + writeFileSync(join(headDir, "a.png"), png([255, 255, 255])); + + const harness = createContext(); + const func = await diffCommand.loader(); + await func.call( + harness.context, + { output: outDir, "no-antialiasing": true }, + baseDir, + headDir + ); + + expect(existsSync(join(outDir, "a.png"))).toBe(true); + }); + test("rejects a missing base directory", async () => { const harness = createContext(); const func = await diffCommand.loader(); diff --git a/test/lib/snapshots/diff.test.ts b/test/lib/snapshots/diff.test.ts index 9208f3aac8..143f514306 100644 --- a/test/lib/snapshots/diff.test.ts +++ b/test/lib/snapshots/diff.test.ts @@ -7,6 +7,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { encode as encodeJpeg } from "jpeg-js"; import { PNG } from "pngjs"; import { afterEach, describe, expect, test } from "vitest"; import { @@ -31,6 +32,22 @@ function png( return PNG.sync.write(image); } +/** Build a solid-color JPEG (RGBA in, JPEG out). */ +function jpeg( + width: number, + height: number, + rgb: [number, number, number] +): Buffer { + const data = Buffer.alloc(width * height * 4); + for (let i = 0; i < data.length; i += 4) { + data[i] = rgb[0]; + data[i + 1] = rgb[1]; + data[i + 2] = rgb[2]; + data[i + 3] = 255; + } + return Buffer.from(encodeJpeg({ data, width, height }, 100).data); +} + const OPTS = { threshold: 0.1, antialiasing: true }; describe("compareImages", () => { @@ -54,7 +71,8 @@ describe("compareImages", () => { expect(result.kind).toBe("changed"); if (result.kind === "changed") { expect(result.diffCount).toBe(16); - expect(result.diffPercentage).toBe(1); + // Percentage (0–100), matching legacy odiff output — all 16 px differ. + expect(result.diffPercentage).toBe(100); expect(result.mask.length).toBeGreaterThan(0); } }); @@ -68,6 +86,27 @@ describe("compareImages", () => { ); expect(result.kind).toBe("layout"); }); + + test("decodes JPEG inputs (identical → match)", () => { + const result = compareImages( + jpeg(4, 4, [20, 40, 60]), + jpeg(4, 4, [20, 40, 60]), + "a.jpg", + OPTS + ); + expect(result.kind).toBe("match"); + }); + + test("throws on undecodable image data", () => { + expect(() => + compareImages( + Buffer.from("not a real png"), + png(4, 4, [0, 0, 0]), + "a.png", + OPTS + ) + ).toThrow(); + }); }); describe("categorizeImages", () => { From 66e0555fa05354adaff6455e85b8e6eca071486e Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Thu, 2 Jul 2026 20:04:58 +0000 Subject: [PATCH 3/3] fix(snapshots): accurate diff hint + collision-safe mask names MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Only claim 'diff masks written' when pixel-changed images produced masks (layout_changed/added/removed write none); reword the no-change hint. - diffMaskRelPath: non-PNG sources append .png (a.jpg → a.jpg.png) so a .png and .jpg with the same stem don't overwrite the same mask. --- src/commands/snapshots/diff.ts | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/commands/snapshots/diff.ts b/src/commands/snapshots/diff.ts index 872e93a041..e653b825b1 100644 --- a/src/commands/snapshots/diff.ts +++ b/src/commands/snapshots/diff.ts @@ -10,7 +10,7 @@ */ import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; -import { basename, dirname, extname, join, resolve } from "node:path"; +import { dirname, extname, join, resolve } from "node:path"; import type { SentryContext } from "../../context.js"; import { buildCommand } from "../../lib/command.js"; import { ValidationError } from "../../lib/errors.js"; @@ -109,11 +109,13 @@ function assertDirectory(path: string, label: string): void { ); } -/** The diff mask path for an image, with a `.png` extension. */ +/** + * The diff mask path for an image (always a PNG). PNG sources keep their name; + * non-PNG sources append `.png` (e.g. `a.jpg` → `a.jpg.png`) so a `.png` and a + * `.jpg` with the same stem don't collide on the same mask file. + */ function diffMaskRelPath(rel: string): string { - const stem = basename(rel, extname(rel)); - const dir = dirname(rel); - return dir === "." ? `${stem}.png` : join(dir, `${stem}.png`); + return extname(rel).toLowerCase() === ".png" ? rel : `${rel}.png`; } /** The base/head/output directories for a diff run. */ @@ -340,18 +342,23 @@ export const diffCommand = buildCommand({ images, }); + // Masks are written only for pixel-`changed` images — not layout_changed, + // added, or removed — so only claim mask output when some were written. + const masksWritten = images.some((img) => img.diffMaskPath !== undefined); + const maskNote = masksWritten ? ` Diff masks written to ${outputDir}.` : ""; + const failures = summary.changed + summary.added + summary.removed + summary.errored; if (flags["fail-on-diff"] && failures > 0) { this.process.exitCode = 1; return { - hint: `${failures} image(s) differed from baseline; diff masks written to ${outputDir}`, + hint: `${failures} image(s) differed from baseline.${maskNote}`, }; } return { hint: - summary.changed > 0 - ? `Diff masks written to ${outputDir}` + failures > 0 + ? `${failures} image(s) differed from baseline.${maskNote}` : "No changes detected.", }; },