diff --git a/README.md b/README.md index b8e55a9..51fdd53 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ tinify config --key=YOUR_KEY ``` This writes `~/.config/tinify/config.json` (on Windows, -`%USERPROFILE%\.config\tinify\config.json`), readable only by you. You only do it once. +`%USERPROFILE%\.config\tinify\config.json`), readable only by you on Linux and macOS; on Windows, your user profile's own permissions protect it. You only do it once. Every run checks the key with Tinify before it uploads anything. A wrong key fails straight away, and the check doesn't count as a compression. @@ -129,19 +129,27 @@ tinify logo.png header.jpg icon.webp tinify ./images ``` -Subfolders are included, but a symlink to a folder isn't followed: name that folder too to include it. A symlink to an image is included. Files that aren't a supported image are skipped. A file named twice, or included by overlapping arguments such as `./images ./images/icons`, is only compressed once. An `--output` folder is never compressed, whether it's inside a folder you name or named itself (as `tinify ./images/* --output=./images/min` does), so a second run doesn't compress its own results again. `--output` naming the folder itself leaves nothing to compress; plain `tinify ./images` compresses in place. +Subfolders are included, but a symlink to a folder isn't followed: name that folder too to include it. A symlink to an image is included. Files that aren't a supported image are skipped. So is what isn't yours to compress, even where it's named like an image: + +- hidden files and folders (names starting with `.`, such as `.thumbnails` or `.git`), unless you add `--hidden`; +- the system's own files, even with `--hidden`: `._` files (macOS metadata), the trash (`.Trash…`, `$RECYCLE.BIN`, `#recycle`, `@Recycle`), NAS thumbnails and snapshots (`@eaDir`, `#snapshot`, `@Recently-Snapshot`), and the `__MACOSX`, `.AppleDouble` and `System Volume Information` folders; +- installed packages (`node_modules`) and photo libraries (`*.photoslibrary`, Lightroom's `*.lrdata` previews), whose files their apps manage. + +A file or folder you name yourself is always included, and `--verbose` lists what was skipped. A file named twice, or included by overlapping arguments such as `./images ./images/icons`, is only compressed once. An `--output` folder is never compressed, whether it's inside a folder you name or named itself (as `tinify ./images/* --output=./images/min` does), so a second run doesn't compress its own results again. `--output` naming the folder itself leaves nothing to compress; plain `tinify ./images` compresses in place. + +Every path you name must exist: if one doesn't, tinify stops before uploading anything. So if `./compressed` doesn't exist yet, `tinify ./images ./compressed` with `--output` left out doesn't compress `./images` in place: it stops and suggests `--output=./compressed`. If `./compressed` does exist, it's just another folder to compress in place. Running `tinify ./images` again skips what it already did, before anything is uploaded: see [Running tinify again](#running-tinify-again). ### Without overwriting the originals -Use `--output` to write results to a different folder. The originals are left untouched. New files (here, or converted ones next to the original) get the original's permissions, less your umask, as `cp` gives them. +Use `--output` to write results to a different folder. The originals are left untouched: an image that `--output` leads back to, because it names the image's own folder or a symlink to it, fails before its upload (leave out `--output` to compress in place). New files (here, or converted ones next to the original) get the original's permissions, less your umask, as `cp` gives them. ```bash tinify ./images --output=./compressed ``` -Folder structure is preserved, so `images/icons/logo.png` becomes `compressed/icons/logo.png`. An image Tinify can't make any smaller is copied there unchanged, so the folder still gets every image. Files already in `./compressed` are not overwritten: see [Existing files and name collisions](#existing-files-and-name-collisions). +Folder structure is preserved, so `images/icons/logo.png` becomes `compressed/icons/logo.png`. With several paths, the folders below the one they share are kept too: `tinify one/logo.png two/logo.png --output=out` writes `out/one/logo.png` and `out/two/logo.png`, and `tinify one two --output=out` writes `out/one/…` and `out/two/…`. An image Tinify can't make any smaller is copied there unchanged, so the folder still gets every image. So is an image tinify already compressed in place (see [Running tinify again](#running-tinify-again)): it isn't uploaded again, and the summary says how many were copied. Files already in `./compressed` are not overwritten: see [Existing files and name collisions](#existing-files-and-name-collisions). ## Converting formats @@ -174,7 +182,7 @@ Two rules decide what counts as an earlier result: - **A pair given together.** With `tinify ./images --convert=webp`, if `a.png` and its `a.webp` are both inputs, both are skipped: `a.png` because its result exists, `a.webp` because it is the result of `a.png`. The cost: an unrelated `photo.webp` next to `photo.png` isn't compressed by `--convert=webp`. - **`--convert=best`.** The result's name is only known once Tinify has picked the format, so any image file with the same name (`.png`, `.jpg`, `.jpeg`, `.webp`, `.avif`, `.jxl`) counts as an earlier result. If that file is also an input, tinify uses [the record](#running-tinify-again) to tell which of the two is the result. When the record doesn't tell, both are skipped as ambiguous, with a warning naming the other file (in JSON, the `skipped` entry's `of`): delete the one that is the result, or rename one. The cost: an unrelated `logo.png` and `logo.jpg` side by side aren't compressed by `--convert=best`. -`--convert` replaces the extension, so two files whose names differ only by extension collide: `pic.avif` and `pic.jxl` both want to become `pic.webp`. The same happens with `--output` when two inputs share a name, such as `a/logo.png` and `b/logo.png`. `tinify` refuses to overwrite the first result, reports the second as a failure, and exits `1`. Rename one of them, or process them in separate runs. +`--convert` replaces the extension, so two files whose names differ only by extension collide: `pic.avif` and `pic.jxl` both want to become `pic.webp`. `tinify` refuses to overwrite the first result, reports the second as a failure, and exits `1`. Rename one of them, or process them in separate runs. Existing results and name collisions are caught before the image is uploaded, so they cost no credit, `--convert=best` included. The one exception is under `--convert=best`: two inputs that turn out to want the same result are only caught after their uploads, so those credits are spent. Uploads to S3 are not checked, so they replace whatever is at that key. @@ -235,6 +243,7 @@ Run `tinify` again on the same images and it skips what it already did, before a - If you delete the record, tinify compresses those images again: it costs credits, and images compressed in place get a second lossy pass. - `--recompress` compresses again what the record lists. Existing results are still skipped. +- With `--output`, an image the record lists is copied to the output folder as it is, without an upload: it is the result, and compressing it again would cost a credit and give it a second lossy pass. That holds when the record lists it with this run's settings: made with the same `--resize`, if you give one, and by `--convert=best`, if you use it. `--convert` to another format doesn't use the record: the image is uploaded, unless its result is already there. - If you edit an image, it's compressed again, but its existing `--output` or `--convert` result is kept: delete it to redo it. - Don't point two runs at the same images at once. @@ -260,7 +269,7 @@ export AWS_REGION=eu-west-1 # optional, defaults to us-east-1 tinify ./images --output=s3://my-bucket/assets/ ``` -The trailing slash matters. `s3://my-bucket/assets/` treats the path as a folder and appends each file's path, keeping subfolders. Without the slash, the path is one exact key: that works for a single image, and is refused for several, since they would overwrite each other. +The trailing slash matters. `s3://my-bucket/assets/` treats the path as a folder and appends each file's path, keeping subfolders as a folder `--output` does. Without the slash, the path is one exact key: that works for a single image, and is refused for several, since they would overwrite each other. With `--convert`, the key gets the new extension (`assets/photo.webp`). `--convert=best` can't upload into a folder, because the extension is only known after converting: pick a format instead. @@ -286,7 +295,7 @@ Each entry of `skipped` has the image's full `path`, an `outputPath` (the existi A result has `unchanged: true` when Tinify couldn't make the image any smaller, so it was left as it is (with `--output`, copied there as it is). Its `output.size` then equals its `input.size`. -`tinify` exits `1` if any file failed, or if the JSON couldn't be written (to a full disk, say), `0` otherwise. A run stopped by Ctrl-C, `kill` or a closed terminal ends killed by that signal, so the shell reports `130`, `143` or `129` (on Windows, those numbers are the exit code). An error before tinify gets to the images, such as a usage error, a missing or rejected key, no image found, or an unusable `--output`, writes no JSON: it prints `tinify: ` and the reason on stderr, and exits `1`. A path you name that doesn't exist, and a folder tinify can't read, are failures: they're listed in `failures` (`not found`, `can't read this folder (EACCES)`), the rest of the run carries on, and tinify exits `1`. If they leave no image at all, that is an error before the images, with no JSON. A broken symlink inside a folder is only a warning. A broken image doesn't stop the rest of the run: it's reported, and the other files still compress. Results are listed in the order the files were given. +`tinify` exits `1` if any file failed, or if the JSON couldn't be written (to a full disk, say), `0` otherwise. A run stopped by Ctrl-C, `kill` or a closed terminal ends killed by that signal, so the shell reports `130`, `143` or `129` (on Windows, those numbers are the exit code). An error before tinify gets to the images, such as a usage error, a path you named that doesn't exist, a missing or rejected key, no image found, or an unusable `--output`, writes no JSON: it prints `tinify: ` and the reason on stderr, and exits `1`. A folder tinify can't read is a failure: it's listed in `failures` (`can't read this folder (EACCES)`), the rest of the run carries on, and tinify exits `1`. If that leaves no image at all, it is an error before the images, with no JSON. A broken symlink inside a folder is only a warning. A broken image doesn't stop the rest of the run: it's reported, and the other files still compress. Results are listed in the order the files were given. Some errors would hit every remaining file, such as an invalid key, a monthly limit that has run out, or a full disk. Those stop the run. An `--output` folder that is a file, or that you can't write to, is refused before anything is uploaded. An in-place result is written into the image itself, so it needs no access to the folder. A folder that a new result goes into (with `--convert`, or a subfolder of `--output`) but that you can't add files to fails only the images going there, before they are uploaded; the rest of the run carries on. A failure whose message starts with `not processed:` had no result written, so a script can tell which files to retry. Those files were never sent, except when Ctrl-C or `kill` stopped one during its upload: that one says `not processed: interrupted during its upload`, may have used a credit, and with an S3 `--output` may have been stored. @@ -299,6 +308,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 | +| `--hidden` | Include hidden files and folders when walking a folder | | `--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 | @@ -321,6 +331,17 @@ Use the environment variable in CI: TINIFY_API_KEY=... tinify ./images --output=./out ``` +## Files tinify keeps + +Besides the images it writes, tinify keeps two files, in `~/.config/tinify/` on Linux and macOS and in `%USERPROFILE%\.config\tinify\` on Windows. The folder is always in your home folder: `XDG_CONFIG_HOME` isn't used. + +| File | What it holds | +| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `config.json` | The API key saved by `tinify config --key=`. On Linux and macOS, the folder and the file are readable only by you; on Windows, your user profile's own permissions protect them. Not written when you use `TINIFY_API_KEY`. | +| `compressed` | [The record](#running-tinify-again) of the images tinify wrote: one line per image, with the settings and the image's SHA-256, never its name or contents. Only ever grows. | + +There is no other cache or log. To forget what tinify compressed, delete `compressed`. To remove everything tinify keeps, key included, delete the folder. + ## Development ```bash diff --git a/src/compress.ts b/src/compress.ts index dd385e1..fca8b3a 100644 --- a/src/compress.ts +++ b/src/compress.ts @@ -5,7 +5,13 @@ import { basename, dirname, extname, join, resolve } from "node:path"; import tinify from "tinify"; import { formatBytes } from "./bytes"; -import { CliError, OutputCollisionError, OutputExistsError, OutputIsInputError } from "./errors"; +import { + CliError, + OutputCollisionError, + OutputExistsError, + OutputIsInputError, + OutputIsItselfError, +} from "./errors"; import { displayPath, realPath, type ResolvedFile } from "./files"; import { type ConvertFormat, @@ -94,6 +100,11 @@ export interface SkippedFile { of?: string; } +/** An image the record knows, copied as it is to a destination that isn't the image itself. */ +export function isCopy(skip: SkippedFile): boolean { + return skip.reason === "already-compressed" && skip.outputPath !== skip.path; +} + export interface CompressSummary { results: CompressResult[]; failures: FileFailure[]; @@ -278,7 +289,12 @@ const SHARED_WRITE_ERRORS = new Set(["ENOSPC", "EDQUOT"]); /** Errors caused by the input file itself. They say nothing about the account or the bucket. */ function isFileSpecific(err: Error): boolean { - if (err instanceof OutputCollisionError || err instanceof OutputExistsError) return true; + if ( + err instanceof OutputCollisionError || + err instanceof OutputExistsError || + err instanceof OutputIsItselfError + ) + return true; if (err instanceof tinify.Error) { // 413: too large; 415: not a supported image. return err instanceof tinify.ClientError && (err.status === 413 || err.status === 415); @@ -318,11 +334,15 @@ function toError(err: unknown): Error { } /** The --verbose line for a skip. An ambiguous one gets a warning instead. */ -function skipLine({ path, outputPath, reason, of }: SkippedFile): string | undefined { +function skipLine(skip: SkippedFile, dryRun: boolean): string | undefined { + const { path, outputPath, reason, of } = skip; const shown = displayPath(path); switch (reason) { - case "already-compressed": - return `skipping ${shown}: already compressed (--recompress to redo)`; + case "already-compressed": { + const why = "already compressed (--recompress to redo)"; + if (!isCopy(skip)) return `skipping ${shown}: ${why}`; + return `${dryRun ? "would copy" : "copied"} ${shown} to ${displayPath(outputPath)}: ${why}`; + } case "result-exists": return `skipping ${shown}: its result ${displayPath(outputPath)} already exists`; case "result-of-input": @@ -376,6 +396,7 @@ async function compressFile( claims.checkNotClaimed(checkPath, file); return { skip: { path: filePath, outputPath: checkPath, reason: "result-exists" } }; } + if (found === "in-place" && target.kind === "dir") throw new OutputIsItselfError(); if (job.outputPath === null) { const earlier = await bestSameName(file, checkPath, inputs, claims, isBestResult); if (earlier) return { skip: earlier }; @@ -480,7 +501,11 @@ async function compressFile( outputPath = resolveOutputPath(file, target, ext); claims.claim(outputPath, file); const found = await findDestination(outputPath, filePath); - if (found === "exists") throw new OutputExistsError(outputPath); + // A folder --output that leads back to the image is refused before the + // upload; here the credit is spent, so it's refused like any file in the way. + if (found === "exists" || (found === "in-place" && target.kind === "dir")) { + throw new OutputExistsError(outputPath); + } await checkWritable(found, outputPath); destination = found; } @@ -579,7 +604,7 @@ export async function compressFiles( }; const skip = (index: number, entry: SkippedFile) => { ui.onFileSkipped(entry); - const line = skipLine(entry); + const line = skipLine(entry, !!options.dryRun); if (line !== undefined) ui.verbose(line); skipped.push([index, entry]); }; diff --git a/src/errors.ts b/src/errors.ts index 8a47bb1..38d2d99 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -49,6 +49,20 @@ export class OutputIsInputError extends OutputExistsError { } } +/** + * --output leads back to the image itself (it names the image's folder, maybe through a + * symlink), so its result would replace the original, which --output promises to keep. + * The image fails before its upload. + */ +export class OutputIsItselfError extends Error { + constructor() { + super( + "not processed: --output leads back to the image itself; leave out --output to compress it in place", + ); + this.name = "OutputIsItselfError"; + } +} + /** Two inputs would write the same result. The second fails. */ export class OutputCollisionError extends Error { constructor(output: string, owner: string) { diff --git a/src/files.ts b/src/files.ts index b5cc16e..51a6ce1 100644 --- a/src/files.ts +++ b/src/files.ts @@ -1,5 +1,6 @@ +import type { Stats } from "node:fs"; import { readdir, realpath, stat } from "node:fs/promises"; -import { basename, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import type { FileFailure } from "./compress"; import { CliError } from "./errors"; @@ -23,9 +24,28 @@ export async function realPath(path: string): Promise { * there would climb out of it (`../..`) or change drives. */ export function displayPath(path: string): string { - const rel = relative(process.cwd(), path); - if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return resolve(path); - return rel || "."; + if (!isWithin(process.cwd(), path)) return resolve(path); + return relative(process.cwd(), path) || "."; +} + +/** Whether `path` is `folder` or below it. */ +function isWithin(folder: string, path: string): boolean { + const rel = relative(folder, path); + return !(rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)); +} + +/** The deepest folder holding all `folders`, or undefined when none does (two Windows drives). */ +function sharedFolder(folders: Iterable): string | undefined { + let shared: string | undefined; + for (const folder of folders) { + shared ??= folder; + while (!isWithin(shared, folder)) { + const up = dirname(shared); + if (up === shared) return undefined; + shared = up; + } + } + return shared; } export interface ResolvedFile { @@ -35,7 +55,7 @@ export interface ResolvedFile { export interface FoundFiles { files: ResolvedFile[]; - /** Named paths that don't exist and folders that can't be read, in argument order, in full. */ + /** Named paths and folders that can't be read, in argument order, in full. */ failures: FileFailure[]; } @@ -48,6 +68,8 @@ interface WalkedFile { interface Walk { /** Real path of the --output folder; a subfolder that is it isn't walked. */ skipRealDir?: string; + /** --hidden: hidden files and folders are taken too. */ + hidden: boolean; verbose?: (message: string) => void; warn: (message: string) => void; /** Appended to, never spread into a call, which breaks on huge folders. */ @@ -55,15 +77,77 @@ interface Walk { failures: FileFailure[]; } -/** `stat` errors meaning the path leads nowhere: missing, under a file, or a symlink loop. */ -const NOT_FOUND = new Set(["ENOENT", "ENOTDIR", "ELOOP"]); +/** + * `stat` errors meaning the path leads nowhere: missing, under a file, a symlink loop, or + * a name no file can have (too long, or characters Windows doesn't allow). + */ +const NOT_FOUND = new Set(["ENOENT", "ENOTDIR", "ELOOP", "ENAMETOOLONG", "EINVAL"]); + +/** + * Folders, lowercased, that hold the system's own files, some named like images: macOS's + * in zip files (__MACOSX), resource forks on network drives (.AppleDouble), thumbnails, + * snapshots and the trash on Synology (@eaDir, #snapshot, #recycle) and QNAP + * (@Recently-Snapshot, @Recycle) NAS drives, the trash on Windows drives ($RECYCLE.BIN), + * and Windows's restore points (System Volume Information). Folders whose names start + * with .Trash (macOS, Linux) are the trash too. + */ +const SYSTEM_FOLDERS = new Set([ + "__macosx", + ".appledouble", + "@eadir", + "#snapshot", + "#recycle", + "@recently-snapshot", + "@recycle", + "$recycle.bin", + "system volume information", +]); + +const HIDDEN = "hidden (--hidden to include it)"; + +/** + * Why a walk leaves out the folder `name`, or undefined to walk it: none of these hold + * the user's own images to compress. A hidden folder is walked with `hidden`. + */ +function skippedFolder(name: string, hidden: boolean): string | undefined { + const lower = name.toLowerCase(); + if (SYSTEM_FOLDERS.has(lower) || lower.startsWith(".trash")) return "system folder"; + if (lower === "node_modules") return "installed packages"; + // macOS Photos and Lightroom: changing their files behind their back can break them. + if (lower.endsWith(".photoslibrary") || lower.endsWith(".lrdata")) { + return "a photo library's own files"; + } + if (!hidden && name.startsWith(".")) return HIDDEN; + return undefined; +} + +/** + * Why a walk leaves out the image `name`, or undefined to take it. macOS writes + * `._` beside each file on drives that can't hold its metadata. + */ +function skippedImage(name: string, hidden: boolean): string | undefined { + if (name.startsWith("._")) return "macOS metadata"; + if (!hidden && name.startsWith(".")) return HIDDEN; + return undefined; +} + +/** + * A path any shell (POSIX, cmd, PowerShell) takes as it is, so a suggested + * `--output=` can be pasted. Quoting differs between them; others get no suggestion. + * Not `\`, which a POSIX shell drops. + */ +const PLAIN_PATH = /^[\p{L}\p{N}._\-/:]+$/u; + +/** A path to suggest: on Windows with `/` for `\`, which Windows takes too. */ +const pasteable = (path: string) => + process.platform === "win32" ? path.replaceAll("\\", "/") : path; /** * Walks `dir`. Messages name it `shown`, as the user would type it: the argument * joined with the path below it. `realDir` is its real path, derived from the input * folder's real path and the relative path, so no syscall is needed per folder. A * folder that can't be read is a failure under its full path, and the walk carries on - * elsewhere. + * elsewhere. The system's own files and folders are left out. */ async function walkDir(dir: string, shown: string, realDir: string, walk: Walk): Promise { const entries = await readdir(dir, { withFileTypes: true }).catch( @@ -81,8 +165,18 @@ async function walkDir(dir: string, shown: string, realDir: string, walk: Walk): walk.verbose?.(`skipping ${shownPath}: it's the --output folder`); continue; } + const skipped = skippedFolder(entry.name, walk.hidden); + if (skipped !== undefined) { + walk.verbose?.(`skipping ${shownPath}: ${skipped}`); + continue; + } await walkDir(fullPath, shownPath, realSub, walk); } else if (isSupportedImage(entry.name)) { + const skipped = skippedImage(entry.name, walk.hidden); + if (skipped !== undefined) { + walk.verbose?.(`skipping ${shownPath}: ${skipped}`); + continue; + } // A symlinked image's real path is its target's; any other file's is derived. // A symlink to nothing is skipped. const realFile = entry.isSymbolicLink() @@ -100,58 +194,104 @@ const depth = (relativePath: string) => relativePath.split(sep).length; * Expands the command-line inputs into image files. A file named twice, or reached * through overlapping inputs (`dir dir/sub`), is listed once, by its real path, under * the path from the outermost folder that reaches it: it is never uploaded (and - * billed) twice. A named path that doesn't exist, or a folder that can't be read, is - * a failure; the rest is still found. With no file left, the failures are warned - * about and nothing is compressed. + * billed) twice. A named path that doesn't exist stops the run, before anything is + * compressed: it is a typo, or a destination given without --output, and the images + * would be compressed in place. A path or folder that can't be read is a failure; the + * rest is still found. With no file left, the failures are warned about and nothing is + * compressed. */ export async function resolveFiles( inputs: string[], warn: (message: string) => void, - options: { outputDir?: string; verbose?: (message: string) => void } = {}, + options: { + outputDir?: string; + /** No --output was given: a missing last path of several may be meant as one. */ + suggestOutput?: boolean; + /** --hidden: walks take hidden files and folders too. */ + hidden?: boolean; + verbose?: (message: string) => void; + } = {}, ): Promise { const skipRealDir = options.outputDir ? await realPath(options.outputDir).catch(() => undefined) : undefined; + // Each image under its path from the named path that reached it, `base`: the named + // folder, or a named file's folder. const found = new Map(); const failures: FileFailure[] = []; - const add = (filePath: string, real: string, relativePath: string) => { + const add = (filePath: string, real: string, base: string) => { + const relativePath = relative(base, filePath); const listed = found.get(real); if (!listed || depth(relativePath) > depth(listed.relativePath)) { found.set(real, { filePath, relativePath }); } }; + // The named folders, and the folders of the other named paths, but not the --output + // folder: the paths below the folder they share depend on the command line only, not + // on what a walk finds. + const bases = new Set(); + // Each named path's stat, or the error it failed with: reported in argument order below. + const named: Array<{ input: string; absPath: string; info: Stats | string }> = []; + const missing: string[] = []; for (const input of inputs) { const absPath = resolve(input); const info = await stat(absPath).catch((err: NodeJS.ErrnoException) => { - const message = NOT_FOUND.has(err.code ?? "") ? "not found" : `can't read it (${err.code})`; - failures.push({ path: absPath, message }); - return null; + if (NOT_FOUND.has(err.code ?? "")) missing.push(input); + return `can't read it (${err.code})`; }); - if (!info) continue; + named.push({ input, absPath, info }); + } + if (missing.length > 0) { + for (const input of missing) warn(`tinify: ${input}: not found`); + const last = inputs.at(-1) ?? ""; + const out = pasteable(last); + const hint = + options.suggestOutput && + inputs.length > 1 && + missing.includes(last) && + !isSupportedImage(last) && + PLAIN_PATH.test(out) + ? `. To write the results to ${out}, use --output=${out}` + : ""; + throw new CliError(`a path you named doesn't exist; nothing was compressed${hint}`); + } - if (info.isDirectory()) { + for (const { input, absPath, info } of named) { + if (typeof info === "string") { + failures.push({ path: absPath, message: info }); + } else if (info.isDirectory()) { // Bun's realpath on macOS fails on a folder it can't read (EACCES), where a walk // would fail on it too: either way, only this folder fails. const realInput = await realPath(absPath).catch((err: NodeJS.ErrnoException) => { failures.push({ path: absPath, message: `can't read this folder (${err.code})` }); return undefined; }); - if (realInput === undefined) continue; if (skipRealDir !== undefined && realInput === skipRealDir) { warn(`tinify: skipping ${input}: it's the --output folder`); continue; } - const walk: Walk = { skipRealDir, verbose: options.verbose, warn, files: [], failures }; + bases.add(absPath); + if (realInput === undefined) continue; + const walk: Walk = { + skipRealDir, + hidden: !!options.hidden, + verbose: options.verbose, + warn, + files: [], + failures, + }; await walkDir(absPath, input, realInput, walk); - for (const f of walk.files) add(f.filePath, f.realPath, relative(absPath, f.filePath)); + for (const f of walk.files) add(f.filePath, f.realPath, absPath); } else if (info.isFile()) { + bases.add(dirname(absPath)); if (isSupportedImage(absPath)) { - add(absPath, await realPath(absPath), basename(absPath)); + add(absPath, await realPath(absPath), dirname(absPath)); } else { warn(`tinify: unsupported format: ${input}`); } } else { + bases.add(dirname(absPath)); warn(`tinify: not a file or folder: ${input}`); } } @@ -160,5 +300,12 @@ export async function resolveFiles( for (const f of failures) warn(`tinify: ${displayPath(f.path)}: ${f.message}`); throw new CliError("no valid image files found"); } - return { files: [...found.values()], failures }; + // Paths below the folder the named paths share keep their folders: one/logo.png and + // two/logo.png stay apart under --output. + const shared = sharedFolder(bases); + const files = [...found.values()].map(({ filePath, relativePath }) => ({ + filePath, + relativePath: shared === undefined ? relativePath : relative(shared, filePath), + })); + return { files, failures }; } diff --git a/src/index.ts b/src/index.ts index 4a5f847..3ff8587 100644 --- a/src/index.ts +++ b/src/index.ts @@ -38,6 +38,7 @@ Options: --convert= Convert to format (see above) --output= Output directory or s3://bucket/path/ --recompress Compress images tinify already compressed again + --hidden Include hidden files and folders when walking a folder --concurrency= 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) @@ -72,6 +73,7 @@ const OPTIONS = { "no-progress": { type: "boolean", default: false }, "dry-run": { type: "boolean", default: false }, recompress: { type: "boolean", default: false }, + hidden: { type: "boolean", default: false }, verbose: { type: "boolean", short: "v", default: false }, help: { type: "boolean", short: "h", default: false }, version: { type: "boolean", short: "V", default: false }, @@ -278,6 +280,8 @@ export async function run(argv: string[], deps: Deps = defaultDeps): Promise ui.error(message), { outputDir: options.output.kind === "dir" ? options.output.dir : undefined, + suggestOutput: options.output.kind === "in-place", + hidden: args.hidden, verbose: (message) => ui.verbose(message), }, ); diff --git a/src/ui.ts b/src/ui.ts index 379696e..801627c 100644 --- a/src/ui.ts +++ b/src/ui.ts @@ -3,12 +3,13 @@ import { basename } from "node:path"; import * as clack from "@clack/prompts"; import { formatBytes } from "./bytes"; -import type { - CompressOptions, - CompressResult, - CompressSummary, - SkippedFile, - SkipReason, +import { + type CompressOptions, + type CompressResult, + type CompressSummary, + isCopy, + type SkippedFile, + type SkipReason, } from "./compress"; import { CliError } from "./errors"; import { displayPath } from "./files"; @@ -165,8 +166,10 @@ function withoutBarStopHandling(start: () => void): void { } } +const ALREADY_COMPRESSED = "already compressed (--recompress to redo)"; + const SKIP_SUMMARY: [SkipReason, string][] = [ - ["already-compressed", "already compressed (--recompress to redo)"], + ["already-compressed", ALREADY_COMPRESSED], ["result-exists", "result already exists (delete it to redo)"], ["result-of-input", "the result of another image"], ["ambiguous", "ambiguous (see the warnings above)"], @@ -229,15 +232,23 @@ function createTuiUI(showProgress: boolean, isVerbose: boolean): UI { clack.log.info(results.map((r) => formatResultLine(r, options)).join("\n")); } + const copies = skipped.filter(isCopy).length; + const skips = skipped.length - copies; const onlySkips = !options.dryRun && results.length === 0 && failures.length === 0 && skipped.length > 0; - const msg = onlySkips - ? `${skipped.length} ${skipped.length === 1 ? "image" : "images"} skipped, nothing to compress` - : summaryMessage(results.length, options, saved); + let msg = summaryMessage(results.length, options, saved); + if (onlySkips && skips === 0) msg = "Nothing to compress"; + else if (onlySkips) + msg = `${skips} ${skips === 1 ? "image" : "images"} skipped, nothing to compress`; if (options.dryRun) clack.log.step(msg); else clack.log.success(msg); + if (copies > 0) { + const copied = options.dryRun ? "would be copied" : "copied"; + const to = options.output.kind === "dir" ? ` to ${displayPath(options.output.dir)}` : ""; + clack.log.info(`${copies} ${copied}${to}: ${ALREADY_COMPRESSED}`); + } for (const [reason, text] of SKIP_SUMMARY) { - const n = skipped.filter((s) => s.reason === reason).length; + const n = skipped.filter((s) => s.reason === reason && !isCopy(s)).length; if (n > 0) clack.log.info(`${n} skipped: ${text}`); } if (failures.length > 0) { diff --git a/tests/compress.test.ts b/tests/compress.test.ts index c62e840..1de8bd2 100644 --- a/tests/compress.test.ts +++ b/tests/compress.test.ts @@ -418,13 +418,86 @@ describe("only the input itself is ever replaced", () => { } }); - test("--output naming the input's own folder replaces the input, as in place", async () => { - const photo = imageFile(dir, "photo.png", 5000); + describe.each([false, true])( + "--output leading back to the image itself (dry run: %p)", + (dryRun) => { + const refused = "not processed: --output leads back to the image itself"; + + test.each([undefined, "webp"] as const)( + "naming its own folder: refused before the upload, the original kept (--convert=%p keeps the name)", + async (convert) => { + const photo = imageFile(dir, convert ? "photo.webp" : "photo.png", 5000); + const { failures } = await compressFiles([photo], opts({ output: dir, convert, dryRun })); + expect(failures).toEqual([ + { + path: photo.filePath, + message: expect.stringMatching(/^not processed: --output leads back/), + }, + ]); + expect(t.default.fromFile).not.toHaveBeenCalled(); + expect(readFileSync(photo.filePath).length).toBe(5000); + }, + ); + + test("naming its folder through a symlink: refused too", async () => { + const photo = imageFile(join(dir, "in"), "photo.png", 5000); + const alias = join(dir, "alias"); + symlinkSync(join(dir, "in"), alias, "dir"); + const { failures } = await compressFiles([photo], opts({ output: alias, dryRun })); + expect(failures[0]?.message).toStartWith(refused); + expect(readFileSync(photo.filePath).length).toBe(5000); + }); - const { failures } = await compressFiles([photo], opts({ output: dir })); + test("--convert=best: refused, as Tinify may pick the image's own format", async () => { + const photo = imageFile(dir, "photo.png", 5000); + const { failures } = await compressFiles( + [photo], + opts({ output: dir, convert: "best", dryRun }), + ); + expect(failures[0]?.message).toStartWith(refused); + expect(t.default.fromFile).not.toHaveBeenCalled(); + }); + test("an image the record knows: refused too, not skipped", async () => { + const photo = imageFile(dir, "photo.png", 5000); + await compressFiles([photo], opts({ record: await record() })); + const { failures, skipped } = await compressFiles( + [photo], + opts({ output: dir, dryRun, record: await record() }), + ); + expect(skipped).toEqual([]); + expect(failures[0]?.message).toStartWith(refused); + }); + }, + ); + + test("--convert=best: a link to the image made at its result's name during the upload is refused", async () => { + const photo = imageFile(join(dir, "in"), "photo.png", 5000); + const before = readFileSync(photo.filePath); + const out = join(dir, "out"); + const link = join(out, "photo.webp"); + t.result.mediaType.mockImplementation(async () => { + if (!existsSync(link)) symlinkSync(photo.filePath, link, "file"); + return "image/webp"; + }); + const { results, failures } = await compressFiles( + [photo], + opts({ output: out, convert: "best", record: await record() }), + ); + expect(results).toEqual([]); + expect(failures).toEqual([ + { path: photo.filePath, message: `${link} already exists; refusing to overwrite it` }, + ]); + expect(readFileSync(photo.filePath)).toEqual(before); + expect((await record()).has(sha256(new Uint8Array(1000)), {})).toBe(false); + }); + + test("--output naming the input's folder with --convert to another format: a new file beside it", async () => { + const photo = imageFile(dir, "photo.png", 5000); + const { failures } = await compressFiles([photo], opts({ output: dir, convert: "webp" })); expect(failures).toEqual([]); - expect(readFileSync(photo.filePath).length).toBe(1000); + expect(readFileSync(photo.filePath).length).toBe(5000); + expect(existsSync(join(dir, "photo.webp"))).toBe(true); }); test("an input reached through a symlink is written in place: the target gets the result", async () => { @@ -442,17 +515,6 @@ describe("only the input itself is ever replaced", () => { expect(lstatSync(link).isSymbolicLink()).toBe(true); }); - test("--output naming the input's folder through a symlink replaces the input, as in place", async () => { - const photo = imageFile(join(dir, "in"), "photo.png", 5000); - const alias = join(dir, "alias"); - symlinkSync(join(dir, "in"), alias, "dir"); - - const { failures } = await compressFiles([photo], opts({ output: alias })); - - expect(failures).toEqual([]); - expect(readFileSync(photo.filePath).length).toBe(1000); - }); - test("--convert=best next to an earlier result: skipped before the upload", async () => { const photo = imageFile(dir, "photo.png"); writeFileSync(join(dir, "photo.avif"), "keep me"); @@ -748,17 +810,6 @@ describe("a result that isn't smaller", () => { }); }); - test("--output naming the input's own folder: nothing written, reported unchanged", async () => { - const photo = imageFile(dir, "photo.png", 1000); - const before = statSync(photo.filePath); - larger(); - const { results, failures } = await compressFiles([photo], opts({ output: dir })); - expect(failures).toEqual([]); - expect(readFileSync(photo.filePath)).toEqual(Buffer.alloc(1000)); - expect(statSync(photo.filePath).mtimeMs).toBe(before.mtimeMs); - expect(results[0]).toMatchObject({ unchanged: true }); - }); - test("--convert or --resize: the result is written even when larger", async () => { larger(); const a = imageFile(dir, "a.png", 1000); @@ -1377,19 +1428,20 @@ describe("the record", () => { expect(skipped).toEqual([ { path: photo.filePath, outputPath: join(out, "photo.png"), reason: "already-compressed" }, ]); + expect(ui.verbose).toHaveBeenCalledWith( + `copied ${photo.filePath} to ${join(out, "photo.png")}: already compressed (--recompress to redo)`, + ); }); - test("--output naming the input's own folder: a recorded image is skipped, nothing written", async () => { + test("--output, dry run: a recorded image would be copied there", async () => { const photo = imageFile(dir, "photo.png", 5000); await compressFiles([photo], opts({ record: await record() })); - const before = statSync(photo.filePath).mtimeMs; - const { skipped, failures } = await compressFiles( - [photo], - opts({ output: dir, record: await record() }), + const out = join(dir, "out"); + await compressFiles([photo], opts({ output: out, dryRun: true, record: await record() })); + expect(existsSync(out)).toBe(false); + expect(ui.verbose).toHaveBeenCalledWith( + `would copy ${photo.filePath} to ${join(out, "photo.png")}: already compressed (--recompress to redo)`, ); - expect(failures).toEqual([]); - expect(skipped?.[0]?.reason).toBe("already-compressed"); - expect(statSync(photo.filePath).mtimeMs).toBe(before); }); test("the line is appended before the image is written", async () => { @@ -1751,14 +1803,16 @@ describe("UI calls", () => { const a = imageFile(dir, "a.png", 1000); const summary = await compressFiles([a], { ...opts(), - inputFailures: [{ path: "gone.png", message: "not found" }], + inputFailures: [{ path: "private", message: "can't read this folder (EACCES)" }], }); - expect(summary.failures).toEqual([{ path: "gone.png", message: "not found" }]); + expect(summary.failures).toEqual([ + { path: "private", message: "can't read this folder (EACCES)" }, + ]); // The progress bar counts them too: each one advances it. expect(ui.start).toHaveBeenCalledWith(2); expect(ui.onFileError).toHaveBeenCalledWith( - "gone.png", - expect.objectContaining({ message: "not found" }), + "private", + expect.objectContaining({ message: "can't read this folder (EACCES)" }), ); }); diff --git a/tests/e2e/commands.test.ts b/tests/e2e/commands.test.ts index 4f86011..88b7e9d 100644 --- a/tests/e2e/commands.test.ts +++ b/tests/e2e/commands.test.ts @@ -197,15 +197,11 @@ describe.each(BUILDS)("%s", (build) => { expect(e().api.requests).toHaveLength(0); }); - test("missing and unsupported inputs are warned about; with no image left, exit 1", async () => { + test("unsupported inputs are warned about; with no image left, exit 1", async () => { const s = e().sandbox(); - const { code, stdout, stderr } = await s.tinify([ - s.path("nope.png"), - touchFile(s.work, "a.txt"), - ]); + const { code, stdout, stderr } = await s.tinify([touchFile(s.work, "a.txt")]); expect(code).toBe(1); expect(stdout).toBe(""); - expect(stderr).toContain("not found"); expect(stderr).toContain("unsupported format"); expect(stderr).toContain("no valid image files found"); }); diff --git a/tests/e2e/compress.test.ts b/tests/e2e/compress.test.ts index f763274..099841b 100644 --- a/tests/e2e/compress.test.ts +++ b/tests/e2e/compress.test.ts @@ -64,20 +64,30 @@ describe.each(BUILDS)("%s", (build) => { expect(stderr).toBe(""); }); - test("a missing input is a failure, an unsupported one a warning; the rest is done", async () => { + test("an unsupported input is a warning; the rest is done", async () => { const s = e().sandbox(); const a = writeImage(s.path("a.png")); writeFileSync(s.path("notes.txt"), "notes"); - const { code, stdout, stderr } = await s.tinify([s.path("nope.png"), s.path("notes.txt"), a]); - expect(code).toBe(1); - expect(parseReport(stdout).failures).toEqual([ - { path: s.path("nope.png"), message: "not found" }, - ]); + const { code, stdout, stderr } = await s.tinify([s.path("notes.txt"), a]); + expect(code).toBe(0); + expect(parseReport(stdout).failures).toBeUndefined(); expect(stderr).toContain("unsupported format"); - expect(stderr).not.toContain("not found"); expectResult(a, "a.png", "image/png"); }); + test("a missing input stops the run before anything is uploaded", async () => { + const s = e().sandbox(); + const a = writeImage(s.path("a.png")); + const before = readFileSync(a); + const { code, stdout, stderr } = await s.tinify([a, s.path("out")]); + expect(code).toBe(1); + expect(stdout).toBe(""); + expect(stderr).toContain(`tinify: ${s.path("out")}: not found`); + expect(stderr).toContain("tinify: a path you named doesn't exist; nothing was compressed"); + expect(readFileSync(a)).toEqual(before); + expect(uploads()).toBe(0); + }); + test.skipIf(IS_WINDOWS || IS_ROOT)( "an unreadable folder is a failure; the rest is compressed", async () => { @@ -273,6 +283,35 @@ describe.each(BUILDS)("%s", (build) => { expect(readFileSync(a)).toEqual(before); }); + test("images of the same name in two named folders keep their folders", async () => { + const s = e().sandbox(); + const one = writeImage(s.path("one", "logo.png"), "png", "one"); + const two = writeImage(s.path("two", "logo.png"), "png", "two"); + const out = s.path("out"); + const { code } = await s.tinify([one, two, `--output=${out}`]); + expect(code).toBe(0); + expectResult(join(out, "one", "logo.png"), "one", "image/png"); + expectResult(join(out, "two", "logo.png"), "two", "image/png"); + }); + + test("naming the folders' shared folder: refused before any upload, originals kept", async () => { + const s = e().sandbox(); + const a = writeImage(s.path("photos", "2024", "a.png")); + writeImage(s.path("photos", "2025", "b.png")); + const before = readFileSync(a); + const { code, stdout } = await s.tinify([ + s.path("photos", "2024"), + s.path("photos", "2025"), + `--output=${s.path("photos")}`, + ]); + expect(code).toBe(1); + expect(parseReport(stdout).failures?.[0]?.message).toStartWith( + "not processed: --output leads back to the image itself", + ); + expect(uploads()).toBe(0); + expect(readFileSync(a)).toEqual(before); + }); + test("naming a file is refused before any upload", async () => { const s = e().sandbox(); const a = writeImage(s.path("a.png")); diff --git a/tests/e2e/trees.test.ts b/tests/e2e/trees.test.ts index 147b8b5..dd1856b 100644 --- a/tests/e2e/trees.test.ts +++ b/tests/e2e/trees.test.ts @@ -101,11 +101,14 @@ describe.each(BUILDS)("%s", (build) => { expect(readdirSync(root).toSorted()).toEqual([NFC, NFD].toSorted()); }); - test("hidden files and folders are walked", async () => { + test("hidden files and folders are walked only with --hidden", async () => { const s = e().sandbox(); const root = s.path("root"); - buildTree(root, { ".hidden.png": image(), ".git/x.png": image() }); + buildTree(root, { "a.png": image(), ".hidden.png": image(), ".git/x.png": image() }); expect((await s.tinify([root])).code).toBe(0); + expect(uploads()).toBe(1); + expect((await s.tinify([root, "--hidden"])).code).toBe(0); + expect(uploads()).toBe(3); expect(isResult(join(root, ".hidden.png"), ".hidden.png")).toBe(true); expect(isResult(join(root, ".git", "x.png"), ".git/x.png")).toBe(true); }); @@ -158,19 +161,54 @@ describe.each(BUILDS)("%s", (build) => { expect(uploads()).toBe(1); }); - test('two symlinks pointing at each other are "not found"', async () => { + test('two symlinks pointing at each other are "not found", which stops the run', async () => { const s = e().sandbox(); buildTree(s.work, { "x.png": { kind: "symlink", target: "y.png", type: "file" }, "y.png": { kind: "symlink", target: "x.png", type: "file" }, "a.png": image(), }); - const { code, stdout } = await s.tinify([s.path("x.png"), s.path("a.png")]); + const { code, stdout, stderr } = await s.tinify([s.path("x.png"), s.path("a.png")]); expect(code).toBe(1); - expect(parseReport(stdout).failures).toEqual([{ path: s.path("x.png"), message: "not found" }]); - expect(isResult(s.path("a.png"), "a.png")).toBe(true); + expect(stdout).toBe(""); + expect(stderr).toContain(`tinify: ${s.path("x.png")}: not found`); + expect(uploads()).toBe(0); }); + test.each([ + ["", [] as string[], ["a.png"]], + [" with --hidden", ["--hidden"], ["a.png", ".thumbnails/b.jpg"]], + ])( + "a walk leaves out the system's files, packages and hidden names%s", + async (_, flags, compressed) => { + const s = e().sandbox(); + const root = s.path("root"); + buildTree(root, { + "a.png": image(), + "._a.png": { kind: "file", text: "AppleDouble" }, + "__MACOSX/._a.png": { kind: "file", text: "AppleDouble" }, + "@eaDir/a.png/SYNOPHOTO_THUMB_M.jpg": image(), + "node_modules/pkg/logo.png": image(), + ".thumbnails/b.jpg": image(), + }); + const before = snapshot(root); + const { code, stdout } = await s.tinify([root, ...flags]); + expect(code).toBe(0); + const shown = (p: string) => join(root, ...p.split("/")); + expect( + parseReport(stdout) + .results.map((r) => r.path) + .toSorted(), + ).toEqual(compressed.map(shown).toSorted()); + expect(uploads()).toBe(compressed.length); + const after = snapshot(root); + const kept = Object.keys(before).filter( + (p) => before[p] !== "dir" && !compressed.includes(p), + ); + for (const path of kept) expect(after[path]).toBe(before[path]); + }, + ); + test("a broken symlink inside a walked folder is a warning", async () => { const s = e().sandbox(); const root = s.path("root"); diff --git a/tests/files.test.ts b/tests/files.test.ts index 48f25a2..cd3bede 100644 --- a/tests/files.test.ts +++ b/tests/files.test.ts @@ -48,6 +48,17 @@ describe("resolveFiles", () => { afterEach(() => cleanDir(dir)); + /** Walks `photos` from `dir`: what it found, and its --verbose lines. */ + const walkPhotos = async (hidden?: boolean) => { + const verbose = mock(() => {}); + const { files, failures } = await inFolder(dir, () => + resolveFiles(["photos"], warn, { verbose, hidden }), + ); + expect(failures).toEqual([]); + expect(warn).not.toHaveBeenCalled(); + return { found: files.map((f) => f.relativePath).toSorted(), verbose }; + }; + test("single file → absolute filePath, basename as relativePath", async () => { const f = touchFile(dir, "image.png"); expect((await resolveFiles([f], warn)).files).toEqual([ @@ -71,20 +82,104 @@ describe("resolveFiles", () => { expect(warn).toHaveBeenCalledWith(expect.stringContaining("unsupported format")); }); - test("a missing path is a failure, not a warning", async () => { - const good = touchFile(dir, "ok.png"); - const gone = join(dir, "nope.png"); - const { files, failures } = await resolveFiles([gone, good], warn); - expect(files.map((f) => f.filePath)).toEqual([good]); - expect(failures).toEqual([{ path: gone, message: "not found" }]); - expect(warn).not.toHaveBeenCalled(); - }); + describe("a named path that doesn't exist", () => { + const stopped = "a path you named doesn't exist; nothing was compressed"; - test("a missing path named from the current folder fails under its full path", async () => { - const good = touchFile(dir, "ok.png"); - await inFolder(dir, async (cwd) => { - const { failures } = await resolveFiles(["nope.png", good], warn); - expect(failures).toEqual([{ path: join(cwd, "nope.png"), message: "not found" }]); + test("stops the run: each is warned about, then CliError", async () => { + const good = touchFile(dir, "ok.png"); + const gone = join(dir, "nope.png"); + const alsoGone = join(dir, "gone"); + await expect(resolveFiles([gone, good, alsoGone], warn)).rejects.toThrow( + new CliError(stopped), + ); + expect(warn.mock.calls).toEqual([ + [`tinify: ${gone}: not found`], + [`tinify: ${alsoGone}: not found`], + ]); + }); + + test("is named as it was typed", async () => { + const good = touchFile(dir, "ok.png"); + await inFolder(dir, async () => { + await expect(resolveFiles([join("sub", "nope.png"), good], warn)).rejects.toThrow(stopped); + }); + expect(warn).toHaveBeenCalledWith(`tinify: ${join("sub", "nope.png")}: not found`); + }); + + test("a name too long for any file is not found either", async () => { + const long = join(dir, "x".repeat(300)); + await expect(resolveFiles([touchFile(dir, "a.png"), long], warn)).rejects.toThrow( + new CliError(stopped), + ); + expect(warn).toHaveBeenCalledWith(`tinify: ${long}: not found`); + }); + + test("stops the run before any folder is walked", async () => { + touchFile(dir, "photos/a.png"); + symlinkSync("gone.png", join(dir, "photos", "link.png"), "file"); + await expect(resolveFiles([join(dir, "photos"), join(dir, "out")], warn)).rejects.toThrow( + stopped, + ); + expect(warn.mock.calls).toEqual([[`tinify: ${join(dir, "out")}: not found`]]); + }); + + test.each([ + ["out", "out"], + [join("web", "fotós-2"), "web/fotós-2"], + ])( + "the last of several, with no --output, may be meant as one: says how (%p)", + async (out, shown) => { + touchFile(dir, "photos/a.png"); + await inFolder(dir, async () => { + await expect( + resolveFiles(["photos", out], warn, { suggestOutput: true }), + ).rejects.toThrow( + new CliError(`${stopped}. To write the results to ${shown}, use --output=${shown}`), + ); + }); + }, + ); + + test.if(IS_WINDOWS)( + "on Windows, the suggestion has / for \\, which every shell leaves alone", + async () => { + touchFile(dir, "photos/a.png"); + await inFolder(dir, async () => { + await expect( + resolveFiles(["photos", ".\\out"], warn, { suggestOutput: true }), + ).rejects.toThrow( + new CliError(`${stopped}. To write the results to ./out, use --output=./out`), + ); + }); + }, + ); + + test.skipIf(IS_WINDOWS)( + "elsewhere, a name with a \\ gets no suggestion: a shell would drop it", + async () => { + touchFile(dir, "photos/a.png"); + await inFolder(dir, async () => { + await expect( + resolveFiles(["photos", "out\\dir"], warn, { suggestOutput: true }), + ).rejects.toThrow(new CliError(stopped)); + }); + }, + ); + + test.each([ + ["with --output", ["photos", "out"], false], + ["the only path", ["out"], true], + ["not the last", ["out", "photos"], true], + ["an image's name", ["photos", "b.png"], true], + ["a name the shell would split", ["photos", "out photos"], true], + ["a name the shell would change", ["photos", "$out"], true], + ])("no --output suggested: %s", async (_, inputs, suggestOutput) => { + touchFile(dir, "photos/a.png"); + await inFolder(dir, async () => { + await expect(resolveFiles(inputs, warn, { suggestOutput })).rejects.toThrow( + new CliError(stopped), + ); + }); }); }); @@ -135,6 +230,26 @@ describe("resolveFiles", () => { chmodSync(join(dir, "private"), 0o755); } }); + + test("failures are in the order the paths were named", async () => { + const priv = join(dir, "private"); + const inside = join(dir, "locked", "b.png"); + touchFile(dir, "private/a.png"); + touchFile(dir, "locked/b.png"); + touchFile(dir, "c.png"); + chmodSync(priv, 0o000); + chmodSync(join(dir, "locked"), 0o000); + try { + const { failures } = await resolveFiles([priv, inside, join(dir, "c.png")], warn); + expect(failures).toEqual([ + { path: priv, message: "can't read this folder (EACCES)" }, + { path: inside, message: "can't read it (EACCES)" }, + ]); + } finally { + chmodSync(priv, 0o755); + chmodSync(join(dir, "locked"), 0o755); + } + }); }); test("a broken symlink inside a folder is a warning", async () => { @@ -155,19 +270,89 @@ describe("resolveFiles", () => { expect(warn).toHaveBeenCalledWith(`tinify: not a file or folder: ${fifo}`); }); - test("nothing left: each failure is warned about, then CliError", async () => { - const gone = join(dir, "nope.png"); - await expect(resolveFiles([gone], warn)).rejects.toThrow("no valid image files found"); - expect(warn).toHaveBeenCalledWith(`tinify: ${gone}: not found`); + describe.skipIf(IS_WINDOWS || IS_ROOT)("nothing left", () => { + test("each failure is warned about, from the current folder, then CliError", async () => { + touchFile(dir, "private/a.png"); + chmodSync(join(dir, "private"), 0o000); + try { + await inFolder(dir, async () => { + await expect(resolveFiles(["private"], warn)).rejects.toThrow( + "no valid image files found", + ); + }); + } finally { + chmodSync(join(dir, "private"), 0o755); + } + expect(warn).toHaveBeenCalledWith(expect.stringMatching(/^tinify: private: can't read/)); + }); }); - test("nothing left: the warning names a path from the current folder", async () => { - await inFolder(dir, async () => { - await expect(resolveFiles([join("sub", "nope.png")], warn)).rejects.toThrow( - "no valid image files found", + describe("what a walk leaves out", () => { + // Left out with or without --hidden. + const ALWAYS = [ + "__MACOSX", + ".AppleDouble", + ".Trashes", + ".Trash", + ".Trash-1000", + "@eaDir", + "#recycle", + "#snapshot", + "@Recycle", + "@Recently-Snapshot", + "$Recycle.Bin", + "System Volume Information", + "node_modules", + "Photos Library.photoslibrary", + "Catalog Previews.lrdata", + ]; + + beforeEach(() => { + touchFile(dir, "photos/a.png"); + touchFile(dir, "photos/._a.png"); + touchFile(dir, "photos/.b.png"); + touchFile(dir, "photos/.thumbnails/c.jpg"); + for (const name of ALWAYS) touchFile(dir, `photos/${name}/d.png`); + }); + + test("system, NAS and package folders, photo libraries, ._ files and hidden names", async () => { + const { found, verbose } = await walkPhotos(); + expect(found).toEqual(["a.png"]); + expect(verbose).toHaveBeenCalledWith(`skipping ${join("photos", "._a.png")}: macOS metadata`); + expect(verbose).toHaveBeenCalledWith(`skipping ${join("photos", "@eaDir")}: system folder`); + expect(verbose).toHaveBeenCalledWith( + `skipping ${join("photos", "node_modules")}: installed packages`, + ); + expect(verbose).toHaveBeenCalledWith( + `skipping ${join("photos", "Photos Library.photoslibrary")}: a photo library's own files`, + ); + expect(verbose).toHaveBeenCalledWith( + `skipping ${join("photos", ".thumbnails")}: hidden (--hidden to include it)`, + ); + expect(verbose).toHaveBeenCalledWith( + `skipping ${join("photos", ".b.png")}: hidden (--hidden to include it)`, ); }); - expect(warn).toHaveBeenCalledWith(`tinify: ${join("sub", "nope.png")}: not found`); + + test("--hidden takes hidden names, but not the system's own", async () => { + const { found } = await walkPhotos(true); + expect(found).toEqual([".b.png", join(".thumbnails", "c.jpg"), "a.png"].toSorted()); + }); + + test("named themselves, they are taken as named", async () => { + const appleDouble = touchFile(dir, "._a.png"); + touchFile(dir, "@eaDir/thumb.jpg"); + touchFile(dir, ".github/logo.png"); + const { files } = await resolveFiles( + [appleDouble, join(dir, "@eaDir"), join(dir, ".github")], + warn, + ); + expect(files.map((f) => f.relativePath)).toEqual([ + "._a.png", + join("@eaDir", "thumb.jpg"), + join(".github", "logo.png"), + ]); + }); }); test("no usable files → CliError", async () => { @@ -204,6 +389,67 @@ describe("resolveFiles", () => { expect(files.find((f) => f.filePath === inner)?.relativePath).toBe(join("sub", "inner.png")); }); + describe("paths are relative to the folder the named paths share", () => { + test("files of the same name in two folders keep their folders", async () => { + const one = touchFile(dir, "one/logo.webp"); + const two = touchFile(dir, "two/logo.webp"); + expect((await resolveFiles([one, two], warn)).files).toEqual([ + { filePath: one, relativePath: join("one", "logo.webp") }, + { filePath: two, relativePath: join("two", "logo.webp") }, + ]); + }); + + test("two named folders keep their names", async () => { + const a = touchFile(dir, "one/a.png"); + const b = touchFile(dir, "two/sub/b.png"); + expect((await resolveFiles([join(dir, "one"), join(dir, "two")], warn)).files).toEqual([ + { filePath: a, relativePath: join("one", "a.png") }, + { filePath: b, relativePath: join("two", "sub", "b.png") }, + ]); + }); + + test("files and folders named from one folder keep the subfolders", async () => { + const top = touchFile(dir, "images/top.png"); + const logo = touchFile(dir, "images/icons/logo.png"); + const { files } = await resolveFiles([top, join(dir, "images", "icons")], warn); + expect(files).toEqual([ + { filePath: top, relativePath: "top.png" }, + { filePath: logo, relativePath: join("icons", "logo.png") }, + ]); + }); + + test("a named folder with no image counts too: the paths don't move once it has one", async () => { + const a = touchFile(dir, "one/a.png"); + mkdirSync(join(dir, "two")); + const named = [join(dir, "one"), join(dir, "two")]; + expect((await resolveFiles(named, warn)).files).toEqual([ + { filePath: a, relativePath: join("one", "a.png") }, + ]); + touchFile(dir, "two/b.png"); + expect((await resolveFiles(named, warn)).files[0]).toEqual({ + filePath: a, + relativePath: join("one", "a.png"), + }); + }); + + test.each([false, true])("--hidden doesn't move an image's path (%p)", async (hidden) => { + const a = touchFile(dir, "images/.keep/a.png"); + const named = [join(dir, "images"), join(dir, "images", ".keep")]; + expect((await resolveFiles(named, warn, { hidden })).files).toEqual([ + { filePath: a, relativePath: join(".keep", "a.png") }, + ]); + }); + + test("the --output folder named as an input doesn't count", async () => { + const a = touchFile(dir, "one/a.png"); + mkdirSync(join(dir, "out")); + const { files } = await resolveFiles([a, join(dir, "out")], warn, { + outputDir: join(dir, "out"), + }); + expect(files).toEqual([{ filePath: a, relativePath: "a.png" }]); + }); + }); + test("a subfolder named before its folder: the folder's path wins, first position kept", async () => { const logo = touchFile(dir, "images/icons/logo.png"); const top = touchFile(dir, "images/top.png"); @@ -225,7 +471,7 @@ describe("resolveFiles", () => { symlinkSync(join(dir, "photos"), join(dir, "photos-link"), "dir"); const { files } = await resolveFiles([join(dir, "photos"), join(dir, "photos-link")], warn); - expect(files).toEqual([{ filePath: a, relativePath: "a.png" }]); + expect(files).toEqual([{ filePath: a, relativePath: join("photos", "a.png") }]); }); test("an image and a symlink to it in one folder are listed once", async () => { diff --git a/tests/main.test.ts b/tests/main.test.ts index 2738936..9b17939 100644 --- a/tests/main.test.ts +++ b/tests/main.test.ts @@ -61,6 +61,7 @@ describe("global flags", () => { expect(help).toContain("--help, -h"); for (const method of ["fit", "scale", "cover", "thumb"]) expect(help).toContain(method); expect(help).toContain("--recompress Compress images tinify already compressed again"); + expect(help).toContain("--hidden Include hidden files and folders"); }); test("no files → usage CliError", async () => { @@ -248,13 +249,15 @@ describe("compressing", () => { await run(argv("a.png", "notes.txt"), deps); expect(deps.resolveFiles).toHaveBeenCalledWith(["a.png", "notes.txt"], expect.any(Function), { outputDir: undefined, + suggestOutput: true, + hidden: false, verbose: expect.any(Function), }); expect(ui.error).toHaveBeenCalledWith("tinify: unsupported format: notes.txt"); }); test("input failures from resolveFiles reach compressFiles", async () => { - const failures = [{ path: "x.png", message: "not found" }]; + const failures = [{ path: "x", message: "can't read this folder (EACCES)" }]; const deps = makeDeps({ resolveFiles: mock(async () => ({ files: [{ filePath: "/abs/a.png", relativePath: "a.png" }], @@ -273,10 +276,25 @@ describe("compressing", () => { await run(argv("photos", "--output=photos/min"), deps); expect(deps.resolveFiles).toHaveBeenCalledWith(["photos"], expect.any(Function), { outputDir: "photos/min", + suggestOutput: false, + hidden: false, verbose: expect.any(Function), }); }); + test.each([ + [[], false], + [["--hidden"], true], + ])("--hidden is passed to resolveFiles (%p)", async (flags, hidden) => { + const deps = makeDeps(); + await run(argv("photos", ...flags), deps); + expect(deps.resolveFiles).toHaveBeenCalledWith( + ["photos"], + expect.any(Function), + expect.objectContaining({ hidden }), + ); + }); + test.each([ ["--json on a TTY", ["--json"], true, "json", {}], ["a TTY", [], true, "tui", { progress: true }], diff --git a/tests/ui.test.ts b/tests/ui.test.ts index 22c55d2..41c393b 100644 --- a/tests/ui.test.ts +++ b/tests/ui.test.ts @@ -677,6 +677,46 @@ describe("TUI mode", () => { expect(Math.max(...clackMock.log.info.mock.invocationCallOrder)).toBeLessThan(failed); }); + test.each([ + [false, "2 copied to out: already compressed (--recompress to redo)"], + [true, "2 would be copied to out: already compressed (--recompress to redo)"], + ])( + "with --output, images already compressed are copied, and the summary says so (dry run: %p)", + async (dryRun, line) => { + const skipped = [ + skipOf(here("a.png"), "already-compressed", { outputPath: here("out", "a.png") }), + skipOf(here("b.png"), "already-compressed", { outputPath: here("out", "b.png") }), + skipOf(here("c.png"), "result-exists", { outputPath: here("out", "c.png") }), + ]; + await createUI("tui", { progress: false }).finish( + { results: [], failures: [failureOf("f.png")], skipped }, + { output: parseOutputTarget("out"), dryRun }, + ); + expect(clackMock.log.info.mock.calls as unknown[][]).toEqual([ + [line], + ["1 skipped: result already exists (delete it to redo)"], + ]); + }, + ); + + test.each([ + ["only copies", 0, "Nothing to compress"], + ["copies and a skip", 1, "1 image skipped, nothing to compress"], + ])("%s: copies aren't counted as skipped", async (_, existing, headline) => { + const copy = (name: string) => + skipOf(here(name), "already-compressed", { outputPath: here("out", name) }); + const skipped = [copy("a.png"), copy("b.png")]; + if (existing) skipped.push(skipOf(here("c.png"), "result-exists")); + await createUI("tui", { progress: false }).finish( + { results: [], failures: [], skipped }, + { output: parseOutputTarget("out") }, + ); + expect(clackMock.log.success).toHaveBeenCalledWith(headline); + expect(clackMock.log.info).toHaveBeenCalledWith( + "2 copied to out: already compressed (--recompress to redo)", + ); + }); + test.each([ [1, "1 image skipped, nothing to compress"], [3, "3 images skipped, nothing to compress"],