FileCache.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. const debug = require('debug')('stylelint:file-cache');
  3. const fileEntryCache = require('file-entry-cache');
  4. const getCacheFile = require('./getCacheFile');
  5. const path = require('path');
  6. const DEFAULT_CACHE_LOCATION = './.stylelintcache';
  7. const DEFAULT_HASH = '';
  8. /** @typedef {import('file-entry-cache').FileDescriptor["meta"] & { hashOfConfig?: string }} CacheMetadata */
  9. /**
  10. * @param {string} [cacheLocation]
  11. * @param {string} [hashOfConfig]
  12. * @constructor
  13. */
  14. class FileCache {
  15. constructor(
  16. cacheLocation = DEFAULT_CACHE_LOCATION,
  17. cwd = process.cwd(),
  18. hashOfConfig = DEFAULT_HASH,
  19. ) {
  20. const cacheFile = path.resolve(getCacheFile(cacheLocation, cwd));
  21. debug(`Cache file is created at ${cacheFile}`);
  22. this._fileCache = fileEntryCache.create(cacheFile);
  23. this._hashOfConfig = hashOfConfig;
  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. /** @type {CacheMetadata} */
  34. const meta = descriptor.meta || {};
  35. const changed = descriptor.changed || meta.hashOfConfig !== this._hashOfConfig;
  36. if (!changed) {
  37. debug(`Skip linting ${absoluteFilepath}. File hasn't changed.`);
  38. }
  39. // Mutate file descriptor object and store config hash to each file.
  40. // Running lint with different config should invalidate the cache.
  41. if (meta.hashOfConfig !== this._hashOfConfig) {
  42. meta.hashOfConfig = this._hashOfConfig;
  43. }
  44. return changed;
  45. }
  46. reconcile() {
  47. this._fileCache.reconcile();
  48. }
  49. destroy() {
  50. this._fileCache.destroy();
  51. }
  52. /**
  53. * @param {string} absoluteFilepath
  54. */
  55. removeEntry(absoluteFilepath) {
  56. this._fileCache.removeEntry(absoluteFilepath);
  57. }
  58. }
  59. module.exports = FileCache;