mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 07:50:13 +00:00
fix(cli): measure answers the four mistakes agents make most (#7443)
* fix(cli): measure answers the four mistakes agents make most The usage errors agents hit most on `measure`: no op named, a path it cannot read, and a flag it does not take. Some agents never get past them to a successful measure. - `measure <video>` with no op (alone or with --json) runs `probe` and says so on stderr. With other flags the op is a guess, so the unknown-command hint asks for one; it now names a path that does not exist yet too. - When ffprobe cannot read a file, the error carries ffprobe's reason and a matching fix: a cut-short download, a page saved as .mp4, a permission. - An unquoted path with spaces says to quote it, both where the extra words are rejected and where the cut path is missing. - Window flags take --from/--to, and folder flags take -o. * refactor(cli): keep comment share at the base in the measure files * test(cli): expect a spaced path as the shell split it, on Windows too * fix(cli): a cut-short MP4 says download it again, read from its header and ffprobe's specific line * fix(cli): an unquoted spaced path reaches probe or its quote hint wherever it falls
This commit is contained in:
+19
-1
@@ -104,7 +104,11 @@ import {
|
||||
type CommandResult,
|
||||
} from "./utils/commandResult.js";
|
||||
import { registerRunningCli } from "./utils/runningCli.js";
|
||||
import { commandWordIndex, openShortcutArgv } from "./utils/projectShortcut.js";
|
||||
import {
|
||||
commandWordIndex,
|
||||
measureProbeShortcutArgv,
|
||||
openShortcutArgv,
|
||||
} from "./utils/projectShortcut.js";
|
||||
|
||||
registerRunningCli();
|
||||
|
||||
@@ -197,6 +201,20 @@ process.argv = [
|
||||
];
|
||||
argv = process.argv.slice(2);
|
||||
|
||||
// `hyperframes measure <video>` is `hyperframes measure probe <video>`.
|
||||
if (argv[commandWordIndex(argv)] === "measure") {
|
||||
const { MEASURE_OPS } = await import("./commands/measure.js");
|
||||
const rewritten = measureProbeShortcutArgv(argv, new Set(MEASURE_OPS));
|
||||
if (rewritten !== argv) {
|
||||
const file = rewritten[rewritten.indexOf("probe") + 1];
|
||||
console.error(
|
||||
`No measure op named: running 'probe ${JSON.stringify(file)}'. Ops: ${MEASURE_OPS.join(", ")}.`,
|
||||
);
|
||||
process.argv = [...process.argv.slice(0, 2), ...rewritten];
|
||||
argv = process.argv.slice(2);
|
||||
}
|
||||
}
|
||||
|
||||
const subCommands = Object.fromEntries(
|
||||
Object.entries(commandLoaders).map(([name, load]) => [name, trackCommandFailures(load)]),
|
||||
);
|
||||
|
||||
@@ -13,23 +13,27 @@ export const examples: Example[] = [
|
||||
["The frames around every event, as strips", "hyperframes measure frames ref.mp4 --events"],
|
||||
];
|
||||
|
||||
const subCommands = {
|
||||
probe: () => import("./measure/probe.js").then((m) => m.default),
|
||||
cuts: () => import("./measure/cuts.js").then((m) => m.default),
|
||||
events: () => import("./measure/events.js").then((m) => m.default),
|
||||
frames: () => import("./measure/frames.js").then((m) => m.default),
|
||||
extract: () => import("./measure/extract.js").then((m) => m.default),
|
||||
curve: () => import("./measure/curve.js").then((m) => m.default),
|
||||
energy: () => import("./measure/energy.js").then((m) => m.default),
|
||||
ink: () => import("./measure/ink.js").then((m) => m.default),
|
||||
look: () => import("./measure/look.js").then((m) => m.default),
|
||||
face: () => import("./measure/face.js").then((m) => m.default),
|
||||
sync: () => import("./measure/sync.js").then((m) => m.default),
|
||||
};
|
||||
|
||||
export const MEASURE_OPS = Object.keys(subCommands);
|
||||
|
||||
export default defineCommand({
|
||||
meta: {
|
||||
name: "measure",
|
||||
description:
|
||||
"Measure a video file as JSON: clock, cuts, events, frames, crops, eases, motion energy, ink, look, faces, lip sync",
|
||||
},
|
||||
subCommands: {
|
||||
probe: () => import("./measure/probe.js").then((m) => m.default),
|
||||
cuts: () => import("./measure/cuts.js").then((m) => m.default),
|
||||
events: () => import("./measure/events.js").then((m) => m.default),
|
||||
frames: () => import("./measure/frames.js").then((m) => m.default),
|
||||
extract: () => import("./measure/extract.js").then((m) => m.default),
|
||||
curve: () => import("./measure/curve.js").then((m) => m.default),
|
||||
energy: () => import("./measure/energy.js").then((m) => m.default),
|
||||
ink: () => import("./measure/ink.js").then((m) => m.default),
|
||||
look: () => import("./measure/look.js").then((m) => m.default),
|
||||
face: () => import("./measure/face.js").then((m) => m.default),
|
||||
sync: () => import("./measure/sync.js").then((m) => m.default),
|
||||
},
|
||||
subCommands,
|
||||
});
|
||||
|
||||
@@ -39,8 +39,8 @@ export default defineCommand({
|
||||
},
|
||||
args: {
|
||||
video: videoArg,
|
||||
start: { type: "string", description: "Window start in seconds (default 0)" },
|
||||
end: { type: "string", description: "Window end in seconds (default: the end)" },
|
||||
start: { type: "string", alias: ["from"], description: "Window start in seconds (default 0)" },
|
||||
end: { type: "string", alias: ["to"], description: "Window end in seconds (default: the end)" },
|
||||
roi: {
|
||||
...roiArg,
|
||||
description: "Region holding the whole move, overshoot included, and nothing else that moves",
|
||||
|
||||
@@ -17,8 +17,8 @@ export default defineCommand({
|
||||
},
|
||||
args: {
|
||||
video: videoArg,
|
||||
start: { type: "string", description: "First second to read (default 0)" },
|
||||
end: { type: "string", description: "Last second to read (default: the end)" },
|
||||
start: { type: "string", alias: ["from"], description: "First second to read (default 0)" },
|
||||
end: { type: "string", alias: ["to"], description: "Last second to read (default: the end)" },
|
||||
json: jsonArg,
|
||||
},
|
||||
async run({ args }) {
|
||||
|
||||
@@ -98,8 +98,8 @@ export default defineCommand({
|
||||
type: "string",
|
||||
description: "Split the frame into COLSxROWS cells, e.g. 6x10 (default with --map: 4x4)",
|
||||
},
|
||||
start: { type: "string", description: "First second (default 0)" },
|
||||
end: { type: "string", description: "Last second (default: the end)" },
|
||||
start: { type: "string", alias: ["from"], description: "First second (default 0)" },
|
||||
end: { type: "string", alias: ["to"], description: "Last second (default: the end)" },
|
||||
thr: {
|
||||
type: "string",
|
||||
description: "Mean grey-level change of an appear or a cut (default 5)",
|
||||
|
||||
@@ -152,7 +152,7 @@ export default defineCommand({
|
||||
video: videoArg,
|
||||
out: {
|
||||
type: "string",
|
||||
alias: ["output", "output-dir"],
|
||||
alias: ["o", "output", "output-dir"],
|
||||
description: "The file to write: .png/.jpg for a still, .mp4 for a clip",
|
||||
required: true,
|
||||
},
|
||||
|
||||
@@ -180,9 +180,14 @@ export default defineCommand({
|
||||
description: "One strip of consecutive frames per window from measure events --map",
|
||||
default: false,
|
||||
},
|
||||
start: { type: "string", description: "With --events or --every: first second (default 0)" },
|
||||
start: {
|
||||
type: "string",
|
||||
alias: ["from"],
|
||||
description: "With --events or --every: first second (default 0)",
|
||||
},
|
||||
end: {
|
||||
type: "string",
|
||||
alias: ["to"],
|
||||
description: "With --events or --every: last second (default: the end)",
|
||||
},
|
||||
max: {
|
||||
|
||||
@@ -28,8 +28,8 @@ export default defineCommand({
|
||||
},
|
||||
args: {
|
||||
video: videoArg,
|
||||
start: { type: "string", description: "First second (default 0)" },
|
||||
end: { type: "string", description: "Last second (default: the end)" },
|
||||
start: { type: "string", alias: ["from"], description: "First second (default 0)" },
|
||||
end: { type: "string", alias: ["to"], description: "Last second (default: the end)" },
|
||||
fps: { type: "string", description: "Frames sampled per second (default 2)" },
|
||||
roi: roiArg,
|
||||
at: { type: "string", description: "With --grid: the moment to read" },
|
||||
|
||||
@@ -28,8 +28,8 @@ export default defineCommand({
|
||||
args: {
|
||||
video: videoArg,
|
||||
roi: { ...roiArg, description: "The mouth, x,y,w,h in the video's pixels (required)" },
|
||||
start: { type: "string", description: "First second (default 0)" },
|
||||
end: { type: "string", description: "Last second (default: the end)" },
|
||||
start: { type: "string", alias: ["from"], description: "First second (default 0)" },
|
||||
end: { type: "string", alias: ["to"], description: "Last second (default: the end)" },
|
||||
"max-lag-ms": { type: "string", description: "Lags searched each way (default 400)" },
|
||||
json: jsonArg,
|
||||
},
|
||||
|
||||
@@ -47,7 +47,7 @@ export const roiArg = {
|
||||
} as const;
|
||||
export const outArg = {
|
||||
type: "string",
|
||||
alias: ["output", "output-dir"] as string[],
|
||||
alias: ["o", "output", "output-dir"] as string[],
|
||||
description: "Folder for pictures (default .hyperframes/measure/<op>)",
|
||||
} as const;
|
||||
export const jsonArg = {
|
||||
|
||||
@@ -1,10 +1,21 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { selectFirstFrameAfterEach } from "../commands/snapshot.js";
|
||||
import { meanAbsDiff, probeVideo, readClip, readFrames, sumOf, videoClip } from "./media.js";
|
||||
import {
|
||||
Fix,
|
||||
ffprobeReason,
|
||||
meanAbsDiff,
|
||||
missingFileFix,
|
||||
probeVideo,
|
||||
readClip,
|
||||
readFrames,
|
||||
sumOf,
|
||||
unreadableFix,
|
||||
videoClip,
|
||||
} from "./media.js";
|
||||
|
||||
const terms = (n: number) => Array.from({ length: n }, (_, i) => `eq(n\\,${i * 2})`);
|
||||
|
||||
@@ -84,3 +95,87 @@ describe.skipIf(!ffmpeg)("an odd box", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("a path that is not there", () => {
|
||||
it("says the shell dropped a Windows path's backslashes", () => {
|
||||
expect(missingFileFix("D:videoclip.mp4")).toMatch(/dropped the backslashes/);
|
||||
});
|
||||
|
||||
it("otherwise asks for the path from the project folder", () => {
|
||||
expect(missingFileFix(join(tmpdir(), "nope.mp4"))).toBe(
|
||||
"pass the video's path from the project folder",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a file ffprobe cannot read", () => {
|
||||
it("keeps ffprobe's reason without the path it repeats", () => {
|
||||
const err = { stderr: Buffer.from("x.mp4: Invalid data found when processing input\n") };
|
||||
expect(ffprobeReason(err, "x.mp4")).toBe("Invalid data found when processing input");
|
||||
expect(ffprobeReason(new Error("boom"), "x.mp4")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps the specific cause of a cut-short file over ffprobe's generic last line", () => {
|
||||
const err = {
|
||||
stderr: Buffer.from(
|
||||
"[mov,mp4,m4a,3gp,3g2,mj2 @ 0x12e808c00] moov atom not found\nhalf.mp4: Invalid data found when processing input\n",
|
||||
),
|
||||
};
|
||||
const reason = ffprobeReason(err, "half.mp4");
|
||||
expect(reason).toBe("moov atom not found");
|
||||
expect(unreadableFix(reason, true)).toMatch(/download it again/);
|
||||
// A web page named .mp4 gets the same two lines from ffprobe: only the header tells them apart.
|
||||
expect(unreadableFix(reason, false)).toMatch(/not a video/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["moov atom not found", true, /download it again/],
|
||||
["moov atom not found", false, /not a video/],
|
||||
["End of file", false, /download it again/],
|
||||
["Invalid data found when processing input", false, /not a video/],
|
||||
["Permission denied", false, /permissions/],
|
||||
[undefined, false, /pass a video file/],
|
||||
])("answers %s (MP4 header: %s)", (reason, mp4Header, fix) => {
|
||||
expect(unreadableFix(reason, mp4Header)).toMatch(fix);
|
||||
});
|
||||
|
||||
it.skipIf(!ffmpeg)(
|
||||
"tells a cut-short download to download again, not that it is no video",
|
||||
() => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-cut-"));
|
||||
const full = join(dir, "full.mp4");
|
||||
const half = join(dir, "half.mp4");
|
||||
execFileSync("ffmpeg", [
|
||||
...["-v", "error", "-f", "lavfi", "-i", "testsrc=size=640x360:rate=30:duration=4"],
|
||||
...["-pix_fmt", "yuv420p", full],
|
||||
]);
|
||||
const bytes = readFileSync(full);
|
||||
writeFileSync(half, bytes.subarray(0, bytes.length >> 1));
|
||||
try {
|
||||
probeVideo(half);
|
||||
expect.unreachable();
|
||||
} catch (err) {
|
||||
expect((err as Fix).message).toMatch(/moov atom not found/);
|
||||
expect((err as Fix).fix).toMatch(/download it again/);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(!ffmpeg)("puts the reason and its fix on the error", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-probe-"));
|
||||
const page = join(dir, "ref.mp4");
|
||||
writeFileSync(page, "<!doctype html><title>Sign in</title>");
|
||||
try {
|
||||
probeVideo(page);
|
||||
expect.unreachable();
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(Fix);
|
||||
expect((err as Fix).message).toMatch(/^ffprobe cannot read .*: .+/);
|
||||
expect((err as Fix).fix).toMatch(/not a video/);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Decode with ffmpeg into raw arrays, so measuring and comparing need nothing but node and ffmpeg.
|
||||
// Ported from the Studio's viral-clone media.mjs and tool.mjs.
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync } from "node:fs";
|
||||
import { closeSync, existsSync, mkdirSync, openSync, readSync } from "node:fs";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { findFFmpeg, findFFprobe, getFFmpegInstallHint } from "../browser/ffmpeg.js";
|
||||
|
||||
@@ -109,28 +109,86 @@ export function probeSeconds(path: string): number {
|
||||
return Number(text) || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* What to do about a path that is not there. `D:video\clip.mp4` reaches us as `D:videoclip.mp4` (an unquoted
|
||||
* Windows path in bash).
|
||||
*/
|
||||
export function missingFileFix(path: string): string {
|
||||
if (/^[A-Za-z]:[^\\/]/.test(path))
|
||||
return "the shell dropped the backslashes: quote the path or write it with / (D:/video/clip.mp4)";
|
||||
return "pass the video's path from the project folder";
|
||||
}
|
||||
|
||||
const CUT_SHORT = "the file is cut short, as an unfinished download is: download it again";
|
||||
const NOT_A_VIDEO =
|
||||
"this is not a video: check what was saved (a web page saved as .mp4 reads like this)";
|
||||
|
||||
/** ffprobe says "moov atom not found" for any file named .mp4; only an MP4's own header makes it cut short. */
|
||||
const UNREADABLE_CAUSES: readonly { pattern: RegExp; fix: (mp4Header: boolean) => string }[] = [
|
||||
{ pattern: /moov atom not found/i, fix: (mp4Header) => (mp4Header ? CUT_SHORT : NOT_A_VIDEO) },
|
||||
{ pattern: /end of file|partial file/i, fix: () => CUT_SHORT },
|
||||
{ pattern: /permission denied/i, fix: () => "the file cannot be read: check its permissions" },
|
||||
{ pattern: /invalid data found/i, fix: () => NOT_A_VIDEO },
|
||||
];
|
||||
|
||||
/** ffprobe's most specific line on a file it could not read, without the demuxer tag or the path it repeats. */
|
||||
export function ffprobeReason(err: unknown, path: string): string | undefined {
|
||||
const stderr = (err as { stderr?: Buffer | string } | null)?.stderr?.toString() ?? "";
|
||||
const lines = stderr
|
||||
.split(/\r?\n/)
|
||||
.map((line) =>
|
||||
line
|
||||
.replace(/^\[[^\]]*\]\s*/, "")
|
||||
.replace(`${path}: `, "")
|
||||
.trim(),
|
||||
)
|
||||
.filter(Boolean);
|
||||
const specific = UNREADABLE_CAUSES.map(({ pattern }) => lines.find((l) => pattern.test(l))).find(
|
||||
Boolean,
|
||||
);
|
||||
const line = specific ?? lines.at(-1);
|
||||
return line ? line.slice(0, 160) : undefined;
|
||||
}
|
||||
|
||||
/** The fix that goes with ffprobe's reason; `mp4Header` is whether the file starts with an MP4 `ftyp` box. */
|
||||
export function unreadableFix(reason: string | undefined, mp4Header = false): string {
|
||||
const cause = reason ? UNREADABLE_CAUSES.find(({ pattern }) => pattern.test(reason)) : undefined;
|
||||
return cause?.fix(mp4Header) ?? "pass a video file (mp4, mov, webm)";
|
||||
}
|
||||
|
||||
function startsWithMp4Header(path: string): boolean {
|
||||
let fd: number | undefined;
|
||||
try {
|
||||
fd = openSync(path, "r");
|
||||
const head = Buffer.alloc(8);
|
||||
readSync(fd, head, 0, 8, 0);
|
||||
return head.toString("latin1", 4, 8) === "ftyp";
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
/** Size (as displayed, rotation applied), clock and sound of a video. */
|
||||
// fallow-ignore-next-line complexity
|
||||
export function probeVideo(path: string): VideoInfo {
|
||||
if (!existsSync(path))
|
||||
throw new Fix(
|
||||
`no file at ${path}`,
|
||||
// `D:video\clip.mp4` reached us as `D:videoclip.mp4`: an unquoted Windows path in bash.
|
||||
/^[A-Za-z]:[^\\/]/.test(path)
|
||||
? "the shell dropped the backslashes: quote the path or write it with / (D:/video/clip.mp4)"
|
||||
: "pass the video's path from the project folder",
|
||||
);
|
||||
if (!existsSync(path)) throw new Fix(`no file at ${path}`, missingFileFix(path));
|
||||
let json: { streams?: ProbeStream[]; format?: { duration?: string } };
|
||||
try {
|
||||
json = JSON.parse(
|
||||
execFileSync(
|
||||
ffprobeBin(),
|
||||
["-v", "error", "-show_streams", "-show_format", "-of", "json", "--", path],
|
||||
{ maxBuffer: MAX_BUFFER, windowsHide: true },
|
||||
{ maxBuffer: MAX_BUFFER, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] },
|
||||
).toString(),
|
||||
);
|
||||
} catch {
|
||||
throw new Fix(`ffprobe cannot read ${path}`, "pass a video file (mp4, mov, webm)");
|
||||
} catch (err) {
|
||||
const reason = ffprobeReason(err, path);
|
||||
throw new Fix(
|
||||
`ffprobe cannot read ${path}${reason ? `: ${reason}` : ""}`,
|
||||
unreadableFix(reason, startsWithMp4Header(path)),
|
||||
);
|
||||
}
|
||||
const streams = json.streams ?? [];
|
||||
const video = streams.find((s) => s.codec_type === "video");
|
||||
|
||||
@@ -15,10 +15,8 @@ describe("output folder flags", () => {
|
||||
["measure events", events, "out"],
|
||||
["measure extract", extract, "out"],
|
||||
["snapshot", snapshot, "output"],
|
||||
])("%s takes --out, --output and --output-dir", (_name, def, key) => {
|
||||
])("%s takes -o, --out, --output and --output-dir", (_name, def, key) => {
|
||||
const spellings = new Set([key, ...aliases(def, key)]);
|
||||
expect([...spellings].sort()).toEqual(
|
||||
["out", "output", "output-dir"].concat(key === "output" ? ["o"] : []).sort(),
|
||||
);
|
||||
expect([...spellings].sort()).toEqual(["o", "out", "output", "output-dir"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,9 +35,15 @@ describe("fileHint", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("stays quiet at the root, for a missing file, and for a group with no commands", () => {
|
||||
it("names them for a path that does not exist yet too", () => {
|
||||
expect(fileHint("clips/no-such-file.mp4", ["measure"], ops)).toBe(
|
||||
"'clips/no-such-file.mp4' looks like a file; name a command first: 'hyperframes measure <probe|cuts> clips/no-such-file.mp4'.",
|
||||
);
|
||||
});
|
||||
|
||||
it("stays quiet at the root, for a plain word, and for a group with no commands", () => {
|
||||
expect(fileHint("package.json", [], ops)).toBeUndefined();
|
||||
expect(fileHint("no-such-file.mp4", ["measure"], ops)).toBeUndefined();
|
||||
expect(fileHint("prbe", ["measure"], ops)).toBeUndefined();
|
||||
expect(fileHint("package.json", ["measure"], [])).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -75,7 +75,9 @@ export const REDIRECTS_WITH_NEXT_STEP = Object.keys(COMMAND_REDIRECTS).filter(
|
||||
);
|
||||
|
||||
export function fileHint(word: string, path: string[], names: string[]): string | undefined {
|
||||
if (path.length === 0 || names.length === 0 || !existsSync(word)) return undefined;
|
||||
if (path.length === 0 || names.length === 0) return undefined;
|
||||
const kind = existsSync(word) ? "is" : /[\\/]|\.\w{2,4}$/.test(word) ? "looks like" : undefined;
|
||||
if (!kind) return undefined;
|
||||
const group = ["hyperframes", ...path].join(" ");
|
||||
return `'${word}' is a file; name a command first: '${group} <${names.join("|")}> ${word}'.`;
|
||||
return `'${word}' ${kind} a file; name a command first: '${group} <${names.join("|")}> ${word}'.`;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { commandWordIndex, openShortcutArgv } from "./projectShortcut.js";
|
||||
import { commandWordIndex, measureProbeShortcutArgv, openShortcutArgv } from "./projectShortcut.js";
|
||||
|
||||
const commands = new Set(["open", "render", "lint"]);
|
||||
const cwd = mkdtempSync(join(tmpdir(), "hf-shortcut-"));
|
||||
@@ -46,6 +46,48 @@ describe("openShortcutArgv", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("measureProbeShortcutArgv", () => {
|
||||
const ops = new Set(["probe", "cuts", "events"]);
|
||||
writeFileSync(join(cwd, "ref.mp4"), "");
|
||||
writeFileSync(join(cwd, "ref one.mp4"), "");
|
||||
|
||||
it.each([
|
||||
[
|
||||
["measure", "ref.mp4"],
|
||||
["measure", "probe", "ref.mp4"],
|
||||
],
|
||||
[
|
||||
["measure", "ref.mp4", "--json"],
|
||||
["measure", "probe", "ref.mp4", "--json"],
|
||||
],
|
||||
[
|
||||
["--verbose", "measure", "ref.mp4"],
|
||||
["--verbose", "measure", "probe", "ref.mp4"],
|
||||
],
|
||||
[
|
||||
["measure", "ref", "one.mp4"],
|
||||
["measure", "probe", "ref one.mp4"],
|
||||
],
|
||||
[
|
||||
["measure", "ref", "one.mp4", "--json"],
|
||||
["measure", "probe", "ref one.mp4", "--json"],
|
||||
],
|
||||
])("probes %j", (argv, expected) => {
|
||||
expect(measureProbeShortcutArgv(argv, ops, cwd)).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[["measure", "cuts", "ref.mp4"]], // an op was named
|
||||
[["measure", "ref.mp4", "--map"]], // other flags: which op is a guess
|
||||
[["measure", "missing.mp4"]], // not a file
|
||||
[["measure", "my-video"]], // a folder
|
||||
[["measure"]],
|
||||
[["render", "ref.mp4"]],
|
||||
])("leaves %j alone", (argv) => {
|
||||
expect(measureProbeShortcutArgv(argv, ops, cwd)).toEqual(argv);
|
||||
});
|
||||
});
|
||||
|
||||
describe("commandWordIndex", () => {
|
||||
it.each([
|
||||
[["render", "x"], 0],
|
||||
|
||||
@@ -23,3 +23,30 @@ export function openShortcutArgv(
|
||||
}
|
||||
return [...argv.slice(0, at), "open", ...argv.slice(at)];
|
||||
}
|
||||
|
||||
export function measureProbeShortcutArgv(
|
||||
argv: readonly string[],
|
||||
ops: ReadonlySet<string>,
|
||||
cwd: string = process.cwd(),
|
||||
): readonly string[] {
|
||||
const at = commandWordIndex(argv);
|
||||
if (at < 0 || argv[at] !== "measure") return argv;
|
||||
const words = argv.slice(at + 1);
|
||||
if (words.length === 0 || ops.has(words[0]!)) return argv;
|
||||
for (let n = words.length; n > 0; n--) {
|
||||
const file = words.slice(0, n).join(" ");
|
||||
const rest = words.slice(n);
|
||||
if (words.slice(0, n).some((w) => w.startsWith("-"))) continue;
|
||||
if (!rest.every((arg) => arg === "--json")) continue;
|
||||
if (isFile(resolve(cwd, file))) return [...argv.slice(0, at + 1), "probe", file, ...rest];
|
||||
}
|
||||
return argv;
|
||||
}
|
||||
|
||||
function isFile(path: string): boolean {
|
||||
try {
|
||||
return statSync(path).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ArgsDef, CommandDef } from "citty";
|
||||
import audio from "../commands/audio.js";
|
||||
@@ -21,4 +24,37 @@ describe("resolveExtraPositionals", () => {
|
||||
CliUsageError,
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["the positional", (dir: string) => ["measure", "probe", join(dir, "ref"), "one.mp4"]],
|
||||
[
|
||||
"a flag value",
|
||||
(dir: string) => [
|
||||
"measure",
|
||||
"look",
|
||||
join(dir, "a.mp4"),
|
||||
"--compare",
|
||||
join(dir, "ref"),
|
||||
"one.mp4",
|
||||
],
|
||||
],
|
||||
])("says to quote a path the shell split at its spaces in %s", (_label, argvOf) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "hf-extra-"));
|
||||
writeFileSync(join(dir, "ref one.mp4"), "");
|
||||
const error = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const argv = process.argv;
|
||||
process.argv = ["node", "hyperframes", ...argvOf(dir)];
|
||||
const single = { args: { video: { type: "positional" } } } as CommandDef<ArgsDef>;
|
||||
try {
|
||||
expect(() =>
|
||||
resolveExtraPositionals(single, "measure", { _: ["x", "one.mp4"], video: "x" }),
|
||||
).toThrow(CliUsageError);
|
||||
expect(error.mock.calls[0]![0]).toContain(
|
||||
`'${join(dir, "ref")} one.mp4' is one path with spaces: quote it.`,
|
||||
);
|
||||
} finally {
|
||||
process.argv = argv;
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import type { ArgsDef, CommandDef } from "citty";
|
||||
import { CliUsageError } from "./commandResult.js";
|
||||
import { isTextFile } from "./textFile.js";
|
||||
@@ -44,6 +45,18 @@ function usageLine(path: string, args: ArgsDef): string {
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
// An unquoted path with spaces reaches us as several words; the longest run of them that is a file names it.
|
||||
function spacedPath(argv: readonly string[]): string | undefined {
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
let joined = argv[i]!;
|
||||
for (let j = i + 1; j < argv.length && !argv[j]!.startsWith("-"); j++) {
|
||||
joined = `${joined} ${argv[j]}`;
|
||||
if (existsSync(joined)) return joined;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Join a free-text command's trailing words, else throw a usage error naming the extras. */
|
||||
export function resolveExtraPositionals(
|
||||
cmd: CommandDef<ArgsDef>,
|
||||
@@ -66,8 +79,10 @@ export function resolveExtraPositionals(
|
||||
}
|
||||
|
||||
const plural = extra.length === 1 ? "" : "s";
|
||||
const spaced = spacedPath(process.argv.slice(2));
|
||||
const message =
|
||||
`Unexpected extra argument${plural} for hyperframes ${path}: ${extra.join(", ")}\n` +
|
||||
(spaced ? `'${spaced}' is one path with spaces: quote it.\n` : "") +
|
||||
`Usage: ${usageLine(path, args)}`;
|
||||
if (wantsJson(parsed?.json)) console.log(JSON.stringify(jsonFailure("usage_error", message)));
|
||||
else console.error(message);
|
||||
|
||||
Reference in New Issue
Block a user