Mathias Bynens | 79e2cf0 | 2020-05-29 16:46:17 +0200 | [diff] [blame] | 1 | 'use strict'; |
| 2 | |
| 3 | const debug = require('debug')('stylelint:file-cache'); |
| 4 | const fileEntryCache = require('file-entry-cache'); |
| 5 | const getCacheFile = require('./getCacheFile'); |
| 6 | const path = require('path'); |
| 7 | |
| 8 | const DEFAULT_CACHE_LOCATION = './.stylelintcache'; |
| 9 | const DEFAULT_HASH = ''; |
| 10 | |
Tim van der Lippe | efb716a | 2020-12-01 12:54:04 +0000 | [diff] [blame] | 11 | /** @typedef {import('file-entry-cache').FileDescriptor["meta"] & { hashOfConfig?: string }} CacheMetadata */ |
| 12 | |
Mathias Bynens | 79e2cf0 | 2020-05-29 16:46:17 +0200 | [diff] [blame] | 13 | /** |
| 14 | * @param {string} [cacheLocation] |
| 15 | * @param {string} [hashOfConfig] |
| 16 | * @constructor |
| 17 | */ |
| 18 | class 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); |
Tim van der Lippe | efb716a | 2020-12-01 12:54:04 +0000 | [diff] [blame] | 35 | /** @type {CacheMetadata} */ |
Mathias Bynens | 79e2cf0 | 2020-05-29 16:46:17 +0200 | [diff] [blame] | 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 | |
| 68 | module.exports = FileCache; |