forked from OKEAMAH/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind-cache-file.js
More file actions
51 lines (42 loc) · 1.29 KB
/
Copy pathfind-cache-file.js
File metadata and controls
51 lines (42 loc) · 1.29 KB
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
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import findCacheDir from "find-cache-dir";
import { isJson, statSafe } from "./utils.js";
/**
* Find default cache file (`./node_modules/.cache/prettier/.prettier-cache`) using https://github.com/avajs/find-cache-dir
*/
function findDefaultCacheFile() {
const cacheDir =
findCacheDir({ name: "prettier", create: true }) || os.tmpdir();
const cacheFilePath = path.join(cacheDir, ".prettier-cache");
return cacheFilePath;
}
async function findCacheFileFromOption(cacheLocation) {
const cacheFile = path.resolve(cacheLocation);
const stat = await statSafe(cacheFile);
if (stat) {
if (stat.isDirectory()) {
throw new Error(
`Resolved --cache-location '${cacheFile}' is a directory`,
);
}
const data = await fs.readFile(cacheFile, "utf8");
if (!isJson(data)) {
throw new Error(`'${cacheFile}' isn't a valid JSON file`);
}
}
return cacheFile;
}
/**
* @param {string | undefined} cacheLocation
* @returns {Promise<string>}
*/
async function findCacheFile(cacheLocation) {
if (!cacheLocation) {
return findDefaultCacheFile();
}
const cacheFile = await findCacheFileFromOption(cacheLocation);
return cacheFile;
}
export default findCacheFile;