/
config-cache.ts
85 lines (75 loc) · 2.25 KB
/
config-cache.ts
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
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
import * as path from "path";
import { findUpSync } from "find-up";
import { CI } from "./is-ci";
import isInteractive from "./is-interactive";
import { logger } from "./logger";
let cacheMessageShown = false;
let __cacheFolder: string | null | undefined;
function getCacheFolder() {
if (__cacheFolder || __cacheFolder === null) return __cacheFolder;
const closestNodeModulesDirectory = findUpSync("node_modules", {
type: "directory",
});
__cacheFolder = closestNodeModulesDirectory
? path.join(closestNodeModulesDirectory, ".cache/wrangler")
: null;
if (!__cacheFolder) {
logger.debug("No folder available to cache configuration");
}
return __cacheFolder;
}
const arrayFormatter = new Intl.ListFormat("en", {
style: "long",
type: "conjunction",
});
function showCacheMessage(fields: string[], folder: string) {
if (!cacheMessageShown && isInteractive() && !CI.isCI()) {
if (fields.length > 0) {
logger.debug(
`Retrieving cached values for ${arrayFormatter.format(
fields
)} from ${path.relative(process.cwd(), folder)}`
);
cacheMessageShown = true;
}
}
}
export function getConfigCache<T>(fileName: string): Partial<T> {
try {
const cacheFolder = getCacheFolder();
if (cacheFolder) {
const configCacheLocation = path.join(cacheFolder, fileName);
const configCache = JSON.parse(
readFileSync(configCacheLocation, "utf-8")
);
showCacheMessage(Object.keys(configCache), cacheFolder);
return configCache;
} else return {};
} catch (err) {
return {};
}
}
export function saveToConfigCache<T>(
fileName: string,
newValues: Partial<T>
): void {
const cacheFolder = getCacheFolder();
if (cacheFolder) {
logger.debug(`Saving to cache: ${JSON.stringify(newValues)}`);
const configCacheLocation = path.join(cacheFolder, fileName);
const existingValues = getConfigCache(fileName);
mkdirSync(path.dirname(configCacheLocation), { recursive: true });
writeFileSync(
configCacheLocation,
JSON.stringify({ ...existingValues, ...newValues }, null, 2)
);
}
}
export function purgeConfigCaches() {
const cacheFolder = getCacheFolder();
if (cacheFolder) {
rmSync(cacheFolder, { recursive: true, force: true });
}
__cacheFolder = undefined;
}