const { execFileSync } = require('node:child_process'); const fs = require('node:fs'); const path = require('node:path'); const sharp = require('sharp'); const repo = process.cwd(); const rel = process.argv[2]; const outDir = process.argv[3] || '/tmp/vsdiff'; const oldRef = process.argv[4] || '1396666'; fs.mkdirSync(outDir, { recursive: true }); const oldBuf = execFileSync('git', ['show', `${oldRef}:${rel}`], { maxBuffer: 1 << 28 }); fs.writeFileSync(path.join(outDir, 'old.png'), oldBuf); const newBuf = fs.readFileSync(path.join(repo, rel)); fs.writeFileSync(path.join(outDir, 'new.png'), newBuf); async function raw(f) { const img = sharp(f).ensureAlpha(); const { data, info } = await img.raw().toBuffer({ resolveWithObject: true }); return { data, w: info.width, h: info.height, ch: info.channels }; } (async () => { const a = await raw(path.join(outDir, 'old.png')); const b = await raw(path.join(outDir, 'new.png')); console.log(`old ${a.w}x${a.h} new ${b.w}x${b.h}`); const w = Math.min(a.w, b.w); const rows = Math.min(a.h, b.h); const firstDiffRows = []; for (let y = 0; y < rows; y++) { let diff = 0; const oa = y * a.w * a.ch, ob = y * b.w * b.ch; for (let x = 0; x < w; x++) { for (let c = 0; c < 3; c++) { const d = Math.abs(a.data[oa + x * a.ch + c] - b.data[ob + x * b.ch + c]); if (d > 24) { diff++; if (diff > 40) break; } } if (diff > 40) break; } if (diff > 40) { firstDiffRows.push(y); if (firstDiffRows.length >= 1 && y - firstDiffRows[0] > 400) break; } } if (!firstDiffRows.length) { console.log('no divergence in shared region'); return; } const start = firstDiffRows[0]; let end = start; for (const y of firstDiffRows) end = y; console.log(`first divergent row = ${start}, last in burst = ${end}, burst rows = ${firstDiffRows.length}`); const top = Math.max(0, start - 260); const height = Math.min(b.h - top, 900); await sharp(path.join(outDir, 'new.png')).extract({ left: 0, top, width: b.w, height }).png().toFile(path.join(outDir, 'crop-new.png')); await sharp(path.join(outDir, 'old.png')).extract({ left: 0, top, width: a.w, height: Math.min(a.h - top, 900) }).png().toFile(path.join(outDir, 'crop-old.png')); console.log(`crops written to ${outDir}/crop-{new,old}.png (top=${top}, h=${height})`); })();