sprites/tools/deflopt/tmp.js
Christopher Monsanto b496612b03 Add support for DeflOpt
- fuse and wine do not get along.

- This is the absolute final release of DeflOpt, and it is only
accessible in binary form via archive.org, so we vendored it.
2020-05-01 07:38:36 -04:00

32 lines
853 B
JavaScript

import pathlib from 'path';
import fs from 'fs';
import crypto from 'crypto';
import os from 'os';
function join(...paths) {
return pathlib.join(os.tmpdir(), ...paths);
}
// Adapted from https://stackoverflow.com/a/61312694
function mktemp(prefix) {
return join(`${prefix}.${crypto.randomBytes(6).readUIntLE(0,6).toString(36)}`);
}
export function asTmp(prefix, src, f) {
const parsed = pathlib.parse(src);
const dst = mktemp(prefix + "." + parsed.name) + parsed.ext;
// This has an astronomically low chance of throwing, but if it does, you
// can just restart the build.
fs.copyFileSync(src, dst, fs.constants.COPYFILE_EXCL);
try {
const {changed, ret} = f(dst);
if (changed) {
fs.copyFileSync(dst, src);
}
return ret;
} finally {
fs.unlinkSync(dst);
}
}