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