Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ Some errors would hit every remaining file, such as an invalid key, a monthly li
| `--method=METHOD` | `fit`, `scale`, `cover`, or `thumb`. Requires `--resize` |
| `--output=PATH` | Write to a folder, or to `s3://bucket/path/` |
| `--recompress` | Compress images tinify already compressed again |
| `--concurrency=N` | Compress N images at once. Default `2` |
| `--dry-run` | List what would happen. No API call, no key needed |
| `--` | Treat everything after it as a file name |
| `--json` | Force JSON output |
Expand Down
8 changes: 5 additions & 3 deletions src/compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ export interface CompressOptions {
record?: CompressedRecord;
/** Compress images the record knows again; existing results are still skipped. */
recompress?: boolean;
/** How many images are compressed at once, 1 or more. Default 2. */
concurrency?: number;
}

/** Mirrors the Tinify API response shape, plus path metadata for CLI use. */
Expand Down Expand Up @@ -101,7 +103,7 @@ export interface CompressSummary {
stopped?: { reason: string; notProcessed: number };
}

const CONCURRENCY = 2;
const DEFAULT_CONCURRENCY = 2;

const NO_OUTPUT: CompressResult["output"] = { size: null, type: null, width: null, height: null };

Expand Down Expand Up @@ -662,7 +664,7 @@ export async function compressFiles(
new Promise<void>((settle) => {
wake = settle;
});
const { signal } = options;
const { signal, concurrency = DEFAULT_CONCURRENCY } = options;
const onAbort = () => wake?.();
signal?.addEventListener("abort", onAbort, { once: true });
const running = new Map<Job, Promise<void>>();
Expand All @@ -671,7 +673,7 @@ export async function compressFiles(
while (next < jobs.length) {
if (signal?.aborted) stopReason ??= "interrupted";
if (stopReason !== undefined) break;
if (running.size >= (probingS3 ? 1 : CONCURRENCY)) {
if (running.size >= (probingS3 ? 1 : concurrency)) {
await sleep();
continue;
}
Expand Down
8 changes: 7 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Options:
--convert=<fmt> Convert to format (see above)
--output=<path> Output directory or s3://bucket/path/
--recompress Compress images tinify already compressed again
--concurrency=<n> Images to compress at once (default 2)
--dry-run Show what would be done, without an API key or API calls
--json Force JSON output (default in non-TTY)
--no-progress Disable progress bar
Expand Down Expand Up @@ -65,6 +66,7 @@ const OPTIONS = {
output: { type: "string" },
resize: { type: "string" },
method: { type: "string" },
concurrency: { type: "string" },
key: { type: "string" },
json: { type: "boolean", default: false },
"no-progress": { type: "boolean", default: false },
Expand Down Expand Up @@ -123,19 +125,23 @@ export function parseArgs(argv: string[]) {

/** Turns the compress flags into options, rejecting bad values before any file or network access. */
export function buildCompressOptions(args: ParsedArgs): Omit<CompressOptions, "ui"> {
const { convert, resize, method, "dry-run": dryRun, recompress } = args;
const { convert, resize, method, "dry-run": dryRun, recompress, concurrency } = args;
if (convert !== undefined && !isConvertFormat(convert)) {
throw new CliError(`invalid format: ${convert}. Must be one of: ${CONVERT_FORMATS.join(", ")}`);
}
if (method !== undefined && resize === undefined) {
throw new CliError("--method requires --resize");
}
if (concurrency !== undefined && !/^[1-9]\d*$/.test(concurrency)) {
throw new CliError(`invalid --concurrency: ${concurrency}. Must be a whole number, 1 or more`);
}
return {
output: parseOutputTarget(args.output),
...(convert !== undefined && { convert }),
...(resize !== undefined && { resize: buildResizeOptions(resize, method) }),
...(dryRun && { dryRun }),
...(recompress && { recompress }),
...(concurrency !== undefined && { concurrency: Number(concurrency) }),
};
}

Expand Down
1 change: 1 addition & 0 deletions tests/args.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ describe("parseArgs", () => {
["--output=a=b", "output", "a=b"],
["--resize=800x600", "resize", "800x600"],
["--method=cover", "method", "cover"],
["--concurrency=4", "concurrency", "4"],
])("%s → %s", (flag, field, value) => {
expect(parse("img.png", flag)[field]).toBe(value);
});
Expand Down
24 changes: 24 additions & 0 deletions tests/compress.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1210,6 +1210,30 @@ describe("concurrency", () => {
// Results are reported in input order, not completion order.
expect(results.map((r) => r.relativePath)).toEqual(["slow.png", "a.png", "b.png", "c.png"]);
});

test.each([1, 3])("concurrency: %d keeps that many uploads in flight", async (concurrency) => {
const files = ["a.png", "b.png", "c.png", "d.png", "e.png"].map((n) => imageFile(dir, n));
let inFlight = 0;
let peak = 0;
t.default.fromFile.mockImplementation(() => {
peak = Math.max(peak, ++inFlight);
const toBuffer = async () => {
// Lasts until one upload more than allowed is in flight, or 50 ms: long enough
// for the allowed ones to overlap.
const until = Date.now() + 50;
const tooMany = () => inFlight > concurrency;
while (!tooMany() && Date.now() < until) await Bun.sleep(1);
inFlight--;
return new Uint8Array(1);
};
return { ...t.source, result: () => ({ ...t.result, toBuffer }) } as never;
});

const { results } = await compressFiles(files, opts({ concurrency }));

expect(results).toHaveLength(5);
expect(peak).toBe(concurrency);
});
});

/**
Expand Down
1 change: 1 addition & 0 deletions tests/e2e/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ describe.each(BUILDS)("%s", (build) => {
[[], "usage: tinify <files...>"],
[["a.png", "--convert=tiff"], "invalid format: tiff"],
[["a.png", "--method=cover"], "--method requires --resize"],
[["a.png", "--concurrency=0"], "invalid --concurrency: 0"],
[["register", "--email=a@b.c"], "Unknown option '--email'"],
[["a.png", "--convert"], "'--convert <value>' argument missing"],
[["version", "a.png"], "use ./version"],
Expand Down
14 changes: 14 additions & 0 deletions tests/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ describe("argument errors come before any key lookup or file access", () => {
[["--resize=800x", "--method=cover"], "needs both width and height"],
[["--resize=800x600", "--method=scale"], "takes one dimension"],
[["--output=s3://"], "invalid S3 output"],
[["--concurrency=0"], "invalid --concurrency: 0"],
[["--concurrency=-1"], "invalid --concurrency: -1"],
[["--concurrency=1.5"], "invalid --concurrency: 1.5"],
[["--concurrency=two"], "invalid --concurrency: two"],
[["--concurrency="], "invalid --concurrency: "],
])("%p → %s", async (flags, message) => {
const deps = makeDeps();
await expect(run(argv("a.png", ...flags), deps)).rejects.toThrow(message);
Expand Down Expand Up @@ -191,6 +196,15 @@ describe("compressing", () => {
expect(compressOptions(plain).recompress).toBeUndefined();
});

test("--concurrency is passed through as a number; without it, it's left out", async () => {
const deps = makeDeps();
await run(argv("a.png", "--concurrency=5"), deps);
expect(compressOptions(deps).concurrency).toBe(5);
const plain = makeDeps();
await run(argv("a.png"), plain);
expect(compressOptions(plain).concurrency).toBeUndefined();
});

test.each([[[]], [["--dry-run"]]])(
"%p: the record is loaded once and passed on",
async (flags) => {
Expand Down
Loading