-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
cache.js
121 lines (105 loc) 路 2.69 KB
/
cache.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import path from "path";
import fs from "fs";
import os from "os";
import * as babel from "@babel/core";
import findCacheDir from "find-cache-dir";
const DEFAULT_CACHE_DIR =
findCacheDir({ name: "@babel/register" }) || os.homedir() || os.tmpdir();
const DEFAULT_FILENAME = path.join(
DEFAULT_CACHE_DIR,
`.babel.${babel.version}.${babel.getEnv()}.json`,
);
const FILENAME: string = process.env.BABEL_CACHE_PATH || DEFAULT_FILENAME;
let data: Object = {};
let cacheDisabled = false;
function isCacheDisabled() {
return process.env.BABEL_DISABLE_CACHE ?? cacheDisabled;
}
/**
* Write stringified cache to disk.
*/
export function save() {
if (isCacheDisabled()) return;
let serialised: string = "{}";
try {
serialised = JSON.stringify(data, null, " ");
} catch (err) {
if (err.message === "Invalid string length") {
err.message = "Cache too large so it's been cleared.";
console.error(err.stack);
} else {
throw err;
}
}
try {
fs.mkdirSync(path.dirname(FILENAME), { recursive: true });
fs.writeFileSync(FILENAME, serialised);
} catch (e) {
switch (e.code) {
// workaround https://github.com/nodejs/node/issues/31481
// todo: remove the ENOENT error check when we drop node.js 13 support
case "ENOENT":
case "EACCES":
case "EPERM":
console.warn(
`Babel could not write cache to file: ${FILENAME}
due to a permission issue. Cache is disabled.`,
);
cacheDisabled = true;
break;
case "EROFS":
console.warn(
`Babel could not write cache to file: ${FILENAME}
because it resides in a readonly filesystem. Cache is disabled.`,
);
cacheDisabled = true;
break;
default:
throw e;
}
}
}
/**
* Load cache from disk and parse.
*/
export function load() {
if (isCacheDisabled()) {
data = {};
return;
}
process.on("exit", save);
process.nextTick(save);
let cacheContent;
try {
cacheContent = fs.readFileSync(FILENAME);
} catch (e) {
switch (e.code) {
// check EACCES only as fs.readFileSync will never throw EPERM on Windows
// https://github.com/libuv/libuv/blob/076df64dbbda4320f93375913a728efc40e12d37/src/win/fs.c#L735
case "EACCES":
console.warn(
`Babel could not read cache file: ${FILENAME}
due to a permission issue. Cache is disabled.`,
);
cacheDisabled = true;
/* fall through */
default:
return;
}
}
try {
data = JSON.parse(cacheContent);
} catch {}
}
/**
* Retrieve data from cache.
*/
export function get(): Object {
return data;
}
/**
* Clear the cache object.
*/
export function clear() {
data = {};
}