Skip to content

Commit 03ac229

Browse files
committed
fix(cli): snapshot --keep refuses two times with one name and replaces linked stills
1 parent bb8d189 commit 03ac229

3 files changed

Lines changed: 71 additions & 26 deletions

File tree

‎packages/cli/src/commands/snapshot-contactSheet.test.ts‎

Lines changed: 45 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
import { runCommand } from "citty";
2-
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
2+
import {
3+
existsSync,
4+
linkSync,
5+
lstatSync,
6+
mkdirSync,
7+
mkdtempSync,
8+
readFileSync,
9+
readdirSync,
10+
rmSync,
11+
symlinkSync,
12+
writeFileSync,
13+
} from "node:fs";
314
import { tmpdir } from "node:os";
415
import { join } from "node:path";
516
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
617

718
const capture = vi.hoisted(() => ({
819
evaluate: vi.fn(),
9-
screenshot: vi.fn(async ({ path }: { path: string }) => {
10-
const bytes = Buffer.from("captured PNG");
11-
writeFileSync(path, bytes);
12-
return bytes;
13-
}),
20+
screenshot: vi.fn(async () => Buffer.from("captured PNG")),
1421
closeBrowser: vi.fn(async () => undefined),
1522
closeServer: vi.fn(async () => undefined),
1623
seek: vi.fn(async () => undefined),
@@ -165,11 +172,7 @@ describe("snapshot contact sheet failures", () => {
165172
historyRoot: historyDeps.historyRoot,
166173
ownerWaitMs: 0,
167174
});
168-
capture.screenshot.mockImplementation(async ({ path }: { path: string }) => {
169-
const bytes = Buffer.from("replaced PNG");
170-
writeFileSync(path, bytes);
171-
return bytes;
172-
});
175+
capture.screenshot.mockImplementation(async () => Buffer.from("replaced PNG"));
173176
primePage(2);
174177
try {
175178
await runCommand(snapshotCommand, args);
@@ -209,10 +212,7 @@ describe("snapshot --keep", () => {
209212
});
210213

211214
async function snapshot(at: string, bytes: string) {
212-
capture.screenshot.mockImplementation(async ({ path }: { path: string }) => {
213-
writeFileSync(path, bytes);
214-
return Buffer.from(bytes);
215-
});
215+
capture.screenshot.mockImplementation(async () => Buffer.from(bytes));
216216
primePage(at.split(",").length);
217217
await runCommand(snapshotCommand, {
218218
rawArgs: [project, "--keep", "--at", at, "--no-end", "--describe", "false", "-o", stills],
@@ -229,4 +229,34 @@ describe("snapshot --keep", () => {
229229
expect(readFileSync(join(stills, "at-1.5s.png"), "utf8")).toBe("first PNG");
230230
expect(existsSync(join(stills, "contact-sheet.jpg"))).toBe(false);
231231
});
232+
233+
it("refuses two times that would share a still, before touching the folder", async () => {
234+
await snapshot("1.5", "first PNG");
235+
capture.screenshot.mockClear();
236+
237+
await expect(snapshot("1.5,1.5004", "second PNG")).rejects.toThrow(
238+
"--keep would name both 1.5 and 1.5004 at-1.5s.png",
239+
);
240+
expect(capture.screenshot).not.toHaveBeenCalled();
241+
expect(readFileSync(join(stills, "at-1.5s.png"), "utf8")).toBe("first PNG");
242+
});
243+
244+
it("replaces a linked still without writing through the link", async () => {
245+
mkdirSync(stills, { recursive: true });
246+
const hardVictim = join(project, "hard-victim.png");
247+
writeFileSync(hardVictim, "hard victim");
248+
linkSync(hardVictim, join(stills, "at-0.5s.png"));
249+
const softVictim = join(project, "soft-victim.png");
250+
writeFileSync(softVictim, "soft victim");
251+
if (process.platform !== "win32") symlinkSync(softVictim, join(stills, "at-1.5s.png"));
252+
253+
await snapshot("0.5,1.5", "new PNG");
254+
255+
expect(readFileSync(hardVictim, "utf8")).toBe("hard victim");
256+
expect(readFileSync(softVictim, "utf8")).toBe("soft victim");
257+
for (const still of ["at-0.5s.png", "at-1.5s.png"]) {
258+
expect(lstatSync(join(stills, still)).isFile()).toBe(true);
259+
expect(readFileSync(join(stills, still), "utf8")).toBe("new PNG");
260+
}
261+
});
232262
});

‎packages/cli/src/commands/snapshot.test.ts‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,7 @@ describe("tailFrameTime", () => {
8080
describe("transparent snapshot capture", () => {
8181
it("asks Chrome to retain the alpha channel in review PNGs", () => {
8282
const source = readFileSync(new URL("./snapshot.ts", import.meta.url), "utf8");
83-
expect(source).toContain(
84-
'page.screenshot({ path: framePath, type: "png", omitBackground: true })',
85-
);
83+
expect(source).toContain('page.screenshot({ type: "png", omitBackground: true })');
8684
});
8785

8886
it("exposes --proxy/--no-proxy and forwards the override to the static server", () => {
@@ -935,10 +933,7 @@ describe("snapshot composite recapture", () => {
935933
const injection = source.indexOf("await injectVideoFramesBatch(page, updates)");
936934
const visibility = source.indexOf("await syncVideoFrameVisibility(", injection);
937935
const recapture = source.indexOf("await recaptureSnapshotComposite(page)", visibility);
938-
const finalCapture = source.indexOf(
939-
'page.screenshot({ path: framePath, type: "png"',
940-
recapture,
941-
);
936+
const finalCapture = source.indexOf('page.screenshot({ type: "png"', recapture);
942937
expect(injection).toBeGreaterThan(-1);
943938
expect(visibility).toBeGreaterThan(injection);
944939
expect(recapture).toBeGreaterThan(visibility);

‎packages/cli/src/commands/snapshot.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import { formatLintFindings } from "../utils/lintFormat.js";
4949
import { normalizeErrorMessage } from "../utils/errorMessage.js";
5050
import { serveStaticProjectHtml } from "../utils/staticProjectServer.js";
5151
import { c } from "../ui/colors.js";
52+
import { writeCaptureFileSync } from "../capture/captureFile.js";
5253
import { runCancellableProcess } from "../utils/cancellableProcess.js";
5354
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
5455
import { parseAngle, type Camera } from "./motionShotLayout.js";
@@ -100,6 +101,21 @@ export function formatSnapshotTimestamp(time: number): string {
100101
return `${Number(time.toFixed(3))}s`;
101102
}
102103

104+
/** --keep names a still by its millisecond label, so two distinct times may not share one. */
105+
function assertDistinctKeepNames(times: number[]): void {
106+
const timeByLabel = new Map<string, number>();
107+
for (const time of times) {
108+
const label = formatSnapshotTimestamp(time);
109+
const other = timeByLabel.get(label);
110+
if (other !== undefined && other !== time) {
111+
throw new Error(
112+
`--keep would name both ${other} and ${time} at-${label}.png; pass times at least 1 ms apart`,
113+
);
114+
}
115+
timeByLabel.set(label, time);
116+
}
117+
}
118+
103119
/** Shows media by the runtime's visibility rule. A clip held at the composition end, or past the end of a source
104120
* shorter than its slot, samples one nominal 30fps frame inside the source; FFmpeg has no frame at or past its end. */
105121
export function resolveSnapshotVideoFrameTime(input: {
@@ -849,9 +865,12 @@ async function captureSnapshots(
849865
region,
850866
opts.zoomScale ?? DEFAULT_ZOOM_SCALE,
851867
);
852-
writeFileSync(framePath, buffer);
868+
writeCaptureFileSync(framePath, buffer);
853869
} else {
854-
await page.screenshot({ path: framePath, type: "png", omitBackground: true });
870+
writeCaptureFileSync(
871+
framePath,
872+
await page.screenshot({ type: "png", omitBackground: true }),
873+
);
855874
}
856875
artifacts.push({
857876
id: `${invocation}-${i}`,
@@ -876,7 +895,7 @@ async function captureSnapshots(
876895
);
877896
} else {
878897
const refPath = join(snapshotDir, `ref-${slot}.png`);
879-
writeFileSync(refPath, refPng);
898+
writeCaptureFileSync(refPath, refPng);
880899
const pairPath = join(snapshotDir, `pair-${slot}.jpg`);
881900
const { createContactSheet } = await import("../capture/contactSheet.js");
882901
await createContactSheet([framePath, refPath], pairPath, {
@@ -1005,7 +1024,7 @@ export default defineCommand({
10051024
keep: {
10061025
type: "boolean",
10071026
description:
1008-
"Add to --output instead of clearing it, naming each still at-<seconds>s.png (at-0s, at-1.5s, at-12.25s: no trailing zeros), so snapshotting one moment again replaces only that still. No contact sheet.",
1027+
"Add to --output instead of clearing it, naming each still at-<seconds>s.png (at-0s, at-1.5s, at-12.25s: no trailing zeros), so snapshotting one moment again replaces only that still. Times less than 1 ms apart share a name, so one run may not pass two of them. No contact sheet.",
10091028
default: false,
10101029
},
10111030
zoom: {
@@ -1084,6 +1103,7 @@ export default defineCommand({
10841103
.map((s) => parseFloat(s.trim()))
10851104
.filter((n) => !isNaN(n))
10861105
: undefined;
1106+
if (args.keep === true && atTimestamps) assertDistinctKeepNames(atTimestamps);
10871107
// Gemini frame analysis runs by default (silently skipped if
10881108
// GEMINI_API_KEY is not set). `--describe "custom question"` overrides
10891109
// the default prompt with a targeted question. `--describe false` opts

0 commit comments

Comments
 (0)