Files
test-repo/src/cli/format-results-cache.js
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

94 lines
2.5 KiB
JavaScript
Raw Normal View History

2022-06-11 23:32:32 +09:00
// Inspired by LintResultsCache from ESLint
// https://github.com/eslint/eslint/blob/c2d0a830754b6099a3325e6d3348c3ba983a677a/lib/cli-engine/lint-result-cache.js
2022-06-19 11:28:28 +08:00
import fileEntryCache from "file-entry-cache";
import stringify from "fast-json-stable-stringify";
import { version as prettierVersion } from "../index.js";
import { createHash } from "./utils.js";
2022-06-11 23:32:32 +09:00
const optionsHashCache = new WeakMap();
const nodeVersion = process && process.version;
/**
* @param {*} options
* @returns {string}
*/
function getHashOfOptions(options) {
if (optionsHashCache.has(options)) {
return optionsHashCache.get(options);
}
const hash = createHash(
`${prettierVersion}_${nodeVersion}_${stringify(options)}`
);
optionsHashCache.set(options, hash);
return hash;
}
/**
* @typedef {{ hashOfOptions?: string }} OurMeta
* @typedef {import("file-entry-cache").FileDescriptor} FileDescriptor
*
* @param {import("file-entry-cache").FileDescriptor} fileDescriptor
* @returns {FileDescriptor["meta"] & OurMeta}
*/
function getMetadataFromFileDescriptor(fileDescriptor) {
return fileDescriptor.meta;
}
class FormatResultsCache {
2022-08-06 11:13:37 +08:00
#fileEntryCache;
2022-06-11 23:32:32 +09:00
/**
* @param {string} cacheFileLocation The path of cache file location. (default: `node_modules/.cache/prettier/prettier-cache`)
* @param {string} cacheStrategy
*/
constructor(cacheFileLocation, cacheStrategy) {
const useChecksum = cacheStrategy === "content";
2022-08-06 11:13:37 +08:00
this.#fileEntryCache = fileEntryCache.create(
2022-06-11 23:32:32 +09:00
/* cacheId */ cacheFileLocation,
/* directory */ undefined,
useChecksum
);
}
/**
* @param {string} filePath
* @param {any} options
*/
existsAvailableFormatResultsCache(filePath, options) {
2022-08-06 11:13:37 +08:00
const fileDescriptor = this.#fileEntryCache.getFileDescriptor(filePath);
2022-06-11 23:32:32 +09:00
const hashOfOptions = getHashOfOptions(options);
const meta = getMetadataFromFileDescriptor(fileDescriptor);
const changed =
fileDescriptor.changed || meta.hashOfOptions !== hashOfOptions;
if (fileDescriptor.notFound) {
return false;
}
if (changed) {
return false;
}
return true;
}
/**
* @param {string} filePath
* @param {any} options
*/
setFormatResultsCache(filePath, options) {
2022-08-06 11:13:37 +08:00
const fileDescriptor = this.#fileEntryCache.getFileDescriptor(filePath);
2022-06-11 23:32:32 +09:00
const meta = getMetadataFromFileDescriptor(fileDescriptor);
if (fileDescriptor && !fileDescriptor.notFound) {
meta.hashOfOptions = getHashOfOptions(options);
}
}
reconcile() {
2022-08-06 11:13:37 +08:00
this.#fileEntryCache.reconcile();
2022-06-11 23:32:32 +09:00
}
}
2022-06-19 11:28:28 +08:00
export default FormatResultsCache;