/
tmpdir.js
57 lines (47 loc) · 1.5 KB
/
tmpdir.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* eslint-disable node-core/require-common-first, node-core/required-modules */
'use strict';
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const { debuglog } = require('util');
const debug = debuglog('test/tmpdir');
function rimrafSync(pathname, { spawn = true } = {}) {
const st = (() => {
try {
return fs.lstatSync(pathname);
} catch (e) {
if (fs.existsSync(pathname))
throw new Error(`Something wonky happened rimrafing ${pathname}`);
debug(e);
}
})();
// If (!st) then nothing to do.
if (!st) {
return;
}
// On Windows first try to delegate rmdir to a shell.
if (spawn && process.platform === 'win32' && st.isDirectory()) {
try {
// Try `rmdir` first.
execSync(`rmdir /q /s ${pathname}`, { timeout: 1000 });
} catch (e) {
// Attempt failed. Log and carry on.
debug(e);
}
}
fs.rmdirSync(pathname, { recursive: true, maxRetries: 5 });
}
const testRoot = process.env.NODE_TEST_DIR ?
fs.realpathSync(process.env.NODE_TEST_DIR) : path.resolve(__dirname, '..');
// Using a `.` prefixed name, which is the convention for "hidden" on POSIX,
// gets tools to ignore it by default or by simple rules, especially eslint.
const tmpdirName = '.tmp.' + (process.env.TEST_THREAD_ID || '0');
const tmpPath = path.join(testRoot, tmpdirName);
function refresh(opts = {}) {
rimrafSync(this.path, opts);
fs.mkdirSync(this.path);
}
module.exports = {
path: tmpPath,
refresh
};