Skip to content

Commit

Permalink
fix(cli): use unique temp dir per invocation
Browse files Browse the repository at this point in the history
Fixes #183
  • Loading branch information
JamieMason committed Nov 13, 2021
1 parent ed5e112 commit 7291ded
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { tmpdir } from 'os';
import { join } from 'path';
import { uuid } from './uuid';

export interface IApp {
readonly bundleId: string;
Expand Down Expand Up @@ -39,7 +40,7 @@ export const SUPPORTED_FILE_TYPES = [
...supports.jpegmini,
].filter((value, i, list) => list.indexOf(value) === i);

export const TMPDIR = join(tmpdir(), 'imageoptim-cli');
export const TMPDIR = join(tmpdir(), 'imageoptim-cli', uuid());
export const VERSION = manifest.version;
export const PNGQUANT_NUMBER_OF_COLORS = '256';
export const PNGQUANT_QUALITY = '65-80';
Expand Down
19 changes: 19 additions & 0 deletions src/uuid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Cheaply generate a UUID with a low chance of collisions
* https://stackoverflow.com/a/8809472/745158
*/
export function uuid(): string {
let epoch: number = new Date().getTime();
let sessionLength: number = Date.now() * 1000 || 0;
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (character) => {
let randomNumber: number = Math.random() * 16;
if (epoch > 0) {
randomNumber = (epoch + randomNumber) % 16 | 0;
epoch = Math.floor(epoch / 16);
} else {
randomNumber = (sessionLength + randomNumber) % 16 | 0;
sessionLength = Math.floor(sessionLength / 16);
}
return (character == 'x' ? randomNumber : (randomNumber & 0x7) | 0x8).toString(16);
});
}

0 comments on commit 7291ded

Please sign in to comment.