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
35 changes: 28 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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.

Expand All @@ -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.

Expand All @@ -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.

Expand All @@ -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 |
Expand All @@ -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
Expand Down
39 changes: 32 additions & 7 deletions src/compress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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[];
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if (job.outputPath === null) {
const earlier = await bestSameName(file, checkPath, inputs, claims, isBestResult);
if (earlier) return { skip: earlier };
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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]);
};
Expand Down
14 changes: 14 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading
Loading