Repository navigation
feat: add prepare image cli #58
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| # V1 Prepare Image CLI | ||
|
|
||
| ## Context | ||
|
|
||
| The second implementation slice makes the v1 product runnable without deleting the existing lab commands yet. | ||
| It builds on the pure layout and output path branch. | ||
|
|
||
| ## Decisions | ||
|
|
||
| - Added `prepare-image` as a Bun script and CLI entrypoint. | ||
| - Kept parsing command-local and limited to `<input>`, `--out`, `--border-px`, and `--help`. | ||
| - Added `prepareImage` as the domain entrypoint for probing, layout, FFmpeg export, metadata stripping, and final path reporting. | ||
| - Used `ffprobe` for source dimensions so TIFF and later EXIF-orientation cases can be handled through the media tool boundary. | ||
| - Used one FFmpeg filter graph with a white background and overlay so transparent inputs can composite onto white. | ||
|
|
||
| ## Validation | ||
|
|
||
| - `bun test tests/integration/prepare_image.integration.test.ts` | ||
| - `bunx tsc --noEmit` | ||
| - `biome lint src/cli/prepare_image.ts src/domain/prepare_image.ts tests/integration/prepare_image.integration.test.ts tests/helpers/cli.ts package.json` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import { DEFAULT_PREPARE_IMAGE_BORDER_PX, prepareImage } from "../domain/prepare_image"; | ||
|
|
||
| const USAGE = "Usage: bun run prepare-image <input> --out <file-path> [--border-px <integer>]"; | ||
|
|
||
| type ParsedArgs = { | ||
| inputPath: string; | ||
| outputPath: string; | ||
| borderPx: number; | ||
| }; | ||
|
|
||
| function parseArgs(args: string[]): ParsedArgs | "help" { | ||
| if (args.length === 1 && args[0] === "--help") { | ||
| return "help"; | ||
| } | ||
|
|
||
| const inputPath = args[0]; | ||
| if (!inputPath || inputPath.startsWith("--")) { | ||
| throw new Error(USAGE); | ||
| } | ||
|
|
||
| let outputPath: string | undefined; | ||
| let borderPx = DEFAULT_PREPARE_IMAGE_BORDER_PX; | ||
|
|
||
| for (let index = 1; index < args.length; index += 1) { | ||
| const flag = args[index]; | ||
|
|
||
| if (flag === "--out") { | ||
| outputPath = readFlagValue(args, index, "--out"); | ||
| index += 1; | ||
| continue; | ||
| } | ||
|
|
||
| if (flag === "--border-px") { | ||
| const value = readFlagValue(args, index, "--border-px"); | ||
| borderPx = parseBorderPx(value); | ||
| index += 1; | ||
| continue; | ||
| } | ||
|
|
||
| throw new Error(`Unknown option: ${flag}`); | ||
| } | ||
|
|
||
| if (!outputPath) { | ||
| throw new Error("Missing required --out <file-path>"); | ||
| } | ||
|
|
||
| return { borderPx, inputPath, outputPath }; | ||
| } | ||
|
|
||
| function readFlagValue(args: string[], index: number, flag: string): string { | ||
| const value = args[index + 1]; | ||
| if (!value || value.startsWith("--")) { | ||
| throw new Error(`Missing value for ${flag}`); | ||
| } | ||
|
|
||
| return value; | ||
| } | ||
|
|
||
| function parseBorderPx(value: string): number { | ||
| const parsed = Number.parseInt(value, 10); | ||
| if (!/^\d+$/.test(value) || !Number.isInteger(parsed)) { | ||
| throw new Error("Invalid --border-px value"); | ||
| } | ||
|
|
||
| return parsed; | ||
| } | ||
|
|
||
| try { | ||
| const parsed = parseArgs(Bun.argv.slice(2)); | ||
| if (parsed === "help") { | ||
| console.log(USAGE); | ||
| process.exit(0); | ||
| } | ||
|
|
||
| const result = prepareImage(parsed); | ||
| console.log(result.outputPath); | ||
| } catch (error) { | ||
| console.error(error instanceof Error ? error.message : String(error)); | ||
| process.exit(1); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| import { resolve } from "node:path"; | ||
| import { computePrepareImageLayout, type PrepareImageLayout } from "./prepare_image_layout"; | ||
| import { runFfmpeg, runFfprobe } from "./media_process"; | ||
| import { resolvePrepareImageOutputPath } from "./output_path"; | ||
|
|
||
| export const DEFAULT_PREPARE_IMAGE_BORDER_PX = 165; | ||
|
|
||
| type PrepareImageInput = { | ||
| inputPath: string; | ||
| outputPath: string; | ||
| borderPx?: number; | ||
| }; | ||
|
|
||
| type PrepareImageOutput = { | ||
| outputPath: string; | ||
| layout: PrepareImageLayout; | ||
| }; | ||
|
|
||
| type SourceDimensions = { | ||
| width: number; | ||
| height: number; | ||
| }; | ||
|
|
||
| export function prepareImage(input: PrepareImageInput): PrepareImageOutput { | ||
| const sourcePath = resolve(input.inputPath); | ||
| const outputPath = resolvePrepareImageOutputPath(resolve(input.outputPath)); | ||
| const source = inspectSourceDimensions(sourcePath); | ||
| const layout = computePrepareImageLayout({ | ||
| borderPx: input.borderPx ?? DEFAULT_PREPARE_IMAGE_BORDER_PX, | ||
| sourceHeight: source.height, | ||
| sourceWidth: source.width, | ||
| }); | ||
|
|
||
| const proc = runFfmpeg([ | ||
| "-y", | ||
| "-hide_banner", | ||
| "-loglevel", | ||
| "error", | ||
| "-i", | ||
| sourcePath, | ||
| "-filter_complex", | ||
| buildPrepareImageFilter(layout), | ||
| "-map", | ||
| "[out]", | ||
| "-frames:v", | ||
| "1", | ||
| "-q:v", | ||
| "1", | ||
| "-pix_fmt", | ||
| "yuvj420p", | ||
| "-map_metadata", | ||
| "-1", | ||
| outputPath, | ||
| ]); | ||
|
|
||
| if (proc.exitCode !== 0) { | ||
| throw new Error(`ffmpeg export failed: ${proc.stderr.trim()}`); | ||
| } | ||
|
|
||
| return { layout, outputPath }; | ||
| } | ||
|
|
||
| function inspectSourceDimensions(path: string): SourceDimensions { | ||
| const proc = runFfprobe([ | ||
| "-v", | ||
| "error", | ||
| "-select_streams", | ||
| "v:0", | ||
| "-show_entries", | ||
| "stream=width,height:stream_tags=rotate:stream_side_data=rotation", | ||
| "-of", | ||
| "json", | ||
| path, | ||
| ]); | ||
|
|
||
| if (proc.exitCode !== 0) { | ||
| throw new Error(`ffprobe failed: ${proc.stderr.trim()}`); | ||
| } | ||
|
|
||
| const payload = JSON.parse(proc.stdout) as unknown; | ||
| const stream = getFirstStream(payload); | ||
| const width = getNumber(stream, "width"); | ||
| const height = getNumber(stream, "height"); | ||
| const rotation = getRotation(stream); | ||
|
|
||
| if (rotation === 90 || rotation === 270) { | ||
| return { height: width, width: height }; | ||
| } | ||
|
|
||
| return { height, width }; | ||
| } | ||
|
|
||
| function buildPrepareImageFilter(layout: PrepareImageLayout): string { | ||
| const sourceFilters = []; | ||
| if (layout.sourceCrop) { | ||
| sourceFilters.push( | ||
| `crop=${layout.sourceCrop.width}:${layout.sourceCrop.height}:${layout.sourceCrop.x}:${layout.sourceCrop.y}`, | ||
| ); | ||
| } | ||
| sourceFilters.push(`scale=${layout.renderWidth}:${layout.renderHeight}`, "setsar=1"); | ||
|
|
||
| return [ | ||
| `[0:v]${sourceFilters.join(",")}[fg]`, | ||
| `color=c=white:s=${layout.outputWidth}x${layout.outputHeight}[bg]`, | ||
| `[bg][fg]overlay=${layout.renderOffsetX}:${layout.renderOffsetY}:format=auto,format=yuvj420p[out]`, | ||
| ].join(";"); | ||
| } | ||
|
|
||
| function getFirstStream(value: unknown): Record<string, unknown> { | ||
| if (!isRecord(value) || !Array.isArray(value.streams) || !isRecord(value.streams[0])) { | ||
| throw new Error("ffprobe did not return an image stream"); | ||
| } | ||
|
|
||
| return value.streams[0]; | ||
| } | ||
|
|
||
| function getNumber(record: Record<string, unknown>, key: string): number { | ||
| const value = record[key]; | ||
| if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) { | ||
| throw new Error(`ffprobe returned invalid ${key}`); | ||
| } | ||
|
|
||
| return value; | ||
| } | ||
|
|
||
| function getRotation(stream: Record<string, unknown>): number { | ||
| const tags = stream.tags; | ||
| if (isRecord(tags) && typeof tags.rotate === "string") { | ||
| return normalizeRotation(Number.parseInt(tags.rotate, 10)); | ||
| } | ||
|
|
||
| const sideData = stream.side_data_list; | ||
| if (Array.isArray(sideData)) { | ||
| for (const entry of sideData) { | ||
| if (isRecord(entry) && typeof entry.rotation === "number") { | ||
| return normalizeRotation(entry.rotation); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return 0; | ||
| } | ||
|
|
||
| function normalizeRotation(rotation: number): number { | ||
| if (!Number.isFinite(rotation)) { | ||
| return 0; | ||
| } | ||
|
|
||
| return ((rotation % 360) + 360) % 360; | ||
| } | ||
|
|
||
| function isRecord(value: unknown): value is Record<string, unknown> { | ||
| return typeof value === "object" && value !== null; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import { describe, expect, test } from "bun:test"; | ||
| import { existsSync, mkdtempSync } from "node:fs"; | ||
| import { tmpdir } from "node:os"; | ||
| import { join } from "node:path"; | ||
| import { inspectMedia } from "../../src/domain/media_inspector"; | ||
| import { runPrepareImageCli } from "../helpers/cli"; | ||
|
|
||
| const outDir = mkdtempSync(join(tmpdir(), "passepartout-prepare-image-")); | ||
|
|
||
| describe("prepare-image cli", () => { | ||
| test("prints minimal help", async () => { | ||
| const result = await runPrepareImageCli(["--help"]); | ||
|
|
||
| expect(result.exitCode).toBe(0); | ||
| expect(result.stdout).toBe("Usage: bun run prepare-image <input> --out <file-path> [--border-px <integer>]\n"); | ||
| expect(result.stderr).toBe(""); | ||
| }); | ||
|
|
||
| test("exports a PNG as a JPEG and prints the actual output path", async () => { | ||
| const requestedOut = join(outDir, "photo.png"); | ||
| const result = await runPrepareImageCli([ | ||
| "tests/fixtures/images/landscape_sample_48x32.png", | ||
| "--out", | ||
| requestedOut, | ||
| "--border-px", | ||
| "0", | ||
| ]); | ||
|
|
||
| const actualOut = join(outDir, "photo.jpg"); | ||
| expect(result.exitCode).toBe(0); | ||
| expect(result.stdout).toBe(`${actualOut}\n`); | ||
| expect(result.stderr).toBe(""); | ||
| expect(existsSync(actualOut)).toBe(true); | ||
| expect(inspectMedia(actualOut)).toMatchObject({ height: 32, width: 48 }); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.