UNPKG

1.87 kBJavaScriptView Raw
1'use strict';
2
3const debug = require('debug')('stylelint:file-cache');
4const fileEntryCache = require('file-entry-cache');
5const getCacheFile = require('./getCacheFile');
6const path = require('path');
7
8const DEFAULT_CACHE_LOCATION = './.stylelintcache';
9const DEFAULT_HASH = '';
10
11/** @typedef {import('file-entry-cache').FileDescriptor["meta"] & { hashOfConfig?: string }} CacheMetadata */
12
13/**
14 * @param {string} [cacheLocation]
15 * @param {string} [hashOfConfig]
16 * @constructor
17 */
18class FileCache {
19 constructor(cacheLocation = DEFAULT_CACHE_LOCATION, hashOfConfig = DEFAULT_HASH) {
20 const cacheFile = path.resolve(getCacheFile(cacheLocation, process.cwd()));
21
22 debug(`Cache file is created at ${cacheFile}`);
23 this._fileCache = fileEntryCache.create(cacheFile);
24 this._hashOfConfig = hashOfConfig;
25 }
26
27 /**
28 * @param {string} absoluteFilepath
29 * @return {boolean}
30 */
31 hasFileChanged(absoluteFilepath) {
32 // Get file descriptor compares current metadata against cached
33 // one and stores the result to "changed" prop.w
34 const descriptor = this._fileCache.getFileDescriptor(absoluteFilepath);
35 /** @type {CacheMetadata} */
36 const meta = descriptor.meta || {};
37 const changed = descriptor.changed || meta.hashOfConfig !== this._hashOfConfig;
38
39 if (!changed) {
40 debug(`Skip linting ${absoluteFilepath}. File hasn't changed.`);
41 }
42
43 // Mutate file descriptor object and store config hash to each file.
44 // Running lint with different config should invalidate the cache.
45 if (meta.hashOfConfig !== this._hashOfConfig) {
46 meta.hashOfConfig = this._hashOfConfig;
47 }
48
49 return changed;
50 }
51
52 reconcile() {
53 this._fileCache.reconcile();
54 }
55
56 destroy() {
57 this._fileCache.destroy();
58 }
59
60 /**
61 * @param {string} absoluteFilepath
62 */
63 removeEntry(absoluteFilepath) {
64 this._fileCache.removeEntry(absoluteFilepath);
65 }
66}
67
68module.exports = FileCache;