-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathfind-helpers.js
62 lines (52 loc) · 1.96 KB
/
find-helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const fs = require('fs');
const path = require('path');
const cache = require('./cache');
const traverseDir = require('./traverse-dir');
const resolveRootDir = require('./resolve-root-dir');
const DEFAULT_VALID_HELPER_EXTNAMES = ['.js'];
/**
* Creates a map of helper names to absolute paths to be required.
* @param {Array} helperDirs - list of absolute paths where helpers are to be found
* @param {String} rootDir - Jest execution root directory: root of the directory containing the project package.json
* @param {Array} helperExtensions - Array of valid javascript filename extensions
* @returns {Object} - helper module names mapped to their absolute paths
*/
module.exports = function findHelpers(helperDirs, rootDir, helperExtensions = DEFAULT_VALID_HELPER_EXTNAMES) {
const cachedHelpers = cache.get('foundHelpers');
if (cachedHelpers) return cachedHelpers;
let foundHelpers = {};
if (helperDirs) {
helperDirs.forEach(function(helperDir) {
const dir = resolveRootDir(helperDir, rootDir);
try {
traverseDir(dir, function(filepath) {
if (!helperExtensions.includes(path.extname(filepath))) return;
const fullHelperPath = path.resolve(dir, filepath);
const pathFromBaseDir = path.relative(dir, fullHelperPath);
const helperName = getHelperNameWithoutExtension(pathFromBaseDir);
foundHelpers[helperName] = fullHelperPath;
})
} catch (err) {
if (err.code === 'ENOENT') {
console.warn(
'[handlebars-jest] No such directory for helperDirs:',
dir
);
} else {
throw err;
}
}
});
}
cache.set('foundHelpers', foundHelpers);
return foundHelpers;
};
function getHelperNameWithoutExtension(filepath) {
const basename = path.basename(filepath, path.extname(filepath));
const partialName = filepath
.split(path.sep)
.slice(0, -1)
.concat(basename)
.join(path.sep);
return partialName;
}