getCacheFile.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. const fs = require('fs');
  3. const hash = require('./hash');
  4. const path = require('path');
  5. /**
  6. * Return the cacheFile to be used by stylelint, based on whether the provided parameter is
  7. * a directory or looks like a directory (ends in `path.sep`), in which case the file
  8. * name will be `cacheFile/.cache_hashOfCWD`.
  9. *
  10. * If cacheFile points to a file or looks like a file, then it will just use that file.
  11. *
  12. * @param {string} cacheFile - The name of file to be used to store the cache
  13. * @param {string} cwd - Current working directory. Used for tests
  14. * @returns {string} Resolved path to the cache file
  15. */
  16. module.exports = function getCacheFile(cacheFile, cwd) {
  17. /*
  18. * Make sure path separators are normalized for environment/os.
  19. * Also, keep trailing path separator if present.
  20. */
  21. cacheFile = path.normalize(cacheFile);
  22. const resolvedCacheFile = path.resolve(cwd, cacheFile);
  23. // If the last character passed is a path separator, we assume is a directory.
  24. const looksLikeADirectory = cacheFile[cacheFile.length - 1] === path.sep;
  25. /**
  26. * Return the default cache file name when provided parameter is a directory.
  27. * @returns {string} - Resolved path to the cacheFile
  28. */
  29. function getCacheFileForDirectory() {
  30. return path.join(resolvedCacheFile, `.stylelintcache_${hash(cwd)}`);
  31. }
  32. let fileStats;
  33. try {
  34. fileStats = fs.lstatSync(resolvedCacheFile);
  35. } catch {
  36. fileStats = null;
  37. }
  38. if (looksLikeADirectory || (fileStats && fileStats.isDirectory())) {
  39. // Return path to provided directory with generated file name.
  40. return getCacheFileForDirectory();
  41. }
  42. // Return normalized path to cache file.
  43. return resolvedCacheFile;
  44. };