UNPKG

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