-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
301 lines (262 loc) · 10.5 KB
/
index.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
'use strict';
const fs = require('fs'),
path = require('path'),
debug = require('debug'),
pkg = require('./package.json');
const cwd = process.cwd();
const cwdLength = cwd.length;
const pkgName = pkg?.name || 'file-magik';
const logLevels = ['debug', 'info', 'warn', 'error', 'critital'];
const getDebug = ({level = 'debug', filePath, relFilePath, suffix} = {level: 'debug'})=> {
if (!relFilePath && filePath) {
relFilePath = filePath.substring(cwdLength);
}
// let debugLog = debug(`${pkgName}:${relFilePath || '?'}:${suffix || '?'}:${level}`);
let debugObj = {};
logLevels.forEach((level) => {
debugObj[level] = (...rest) => {
const logLevelPrefix = `${level}:`;
const debugLogger = debug(`${pkgName}:${logLevelPrefix}:${relFilePath || '?'}:${suffix || '?'}`);
// Prefix all logging with date
debugLogger(new Date().toISOString() + ` -- ${logLevelPrefix}`, ...rest);
};
});
return debugObj;
};
const pkgDebugLogger = getDebug();
/**
* Gets all file paths with the given extension. Can optionally do it recursively, and exclude named files and/or
* directories
* @param pathToSearch {String} The base path
* @param extension {String} File extensions to search for
* @param opts {Object}
* recursive : Whether or not to search recursively
* excludeFiles : Files to exclude from the results (without the extension)
* excludeDirectories : Directory names to exclude from recursive search
* @return {*}
*/
exports.get = function getFilePaths (pathToSearch, opts) {
const debugLogger = getDebug({ filePath: pathToSearch });
debugLogger.debug('get init');
if (!pathToSearch) {
return debugLogger.error('pathToSearch not specified');
}
var extension = opts.extension === undefined ? '.js' : opts.extension,
regexMatchPatterns = opts.regexMatchPatterns || [],
excludeFiles = opts.excludeFiles || [],
excludeDirectories = opts.excludeDirectories || [],
directoriesAreIncluded = opts.directoriesAreIncluded || false,
convertDashedNames = typeof opts.convertDashedNames !== 'undefined' ? opts.convertDashedNames : true,
getNames = opts.getNames || false,
results = [];
var files = fs.readdirSync(path.resolve(pathToSearch))
.map(function (fileName) {
return path.resolve(pathToSearch, fileName);
});
debugLogger.debug(`files found:${files.length}`);
files.forEach(function (filePath) {
var fileName = filePath.split(path.sep).pop();
fileName = fileName.substring(0, fileName.length - (extension ? extension.length : 0));
var regexMatches = regexMatchPatterns.filter(function (pattern) {
return typeof pattern !== 'string' && filePath.match(pattern);
}),
regexMatch = regexMatchPatterns.length ? regexMatches.length : true;
var excludePatternMatch = excludeFiles.filter(function (pattern) {
return typeof pattern !== 'string' && filePath.match(pattern);
}).length > 0;
var isFile = fs.statSync(filePath).isFile(),
included =
//not excluded regex pattern
regexMatch && !excludePatternMatch &&
//not excluded file name
excludeFiles.indexOf(fileName) === -1 &&
//have extension & matches, or is directory
((isFile && !extension) || (extension && filePath.substr(-1 * extension.length) === extension) || !isFile) &&
//is a file, or require directories flag true
(isFile || (directoriesAreIncluded && !isFile));
if (included) {
if (!getNames) {
results.push(filePath);
} else {
results.push({name: convertDashedNames ? convertDashedName(fileName) : fileName, path: filePath});
}
} else {
debugLogger.debug(`${filePath} not included based on configured opts`);
}
});
debugLogger.info(`opts.recursive:${opts.recursive}`);
if (!!opts.recursive) {
files.filter(function (directoryPath) {
const isDirectory = fs.statSync(directoryPath).isDirectory();
if (isDirectory) {
const debugLogger = getDebug({ filePath: directoryPath });
debugLogger.debug(`isDirectory:${isDirectory}`);
}
return isDirectory;
}).forEach(function (directoryPath) {
const debugLogger = getDebug({ filePath: directoryPath });
var dirName = directoryPath.split(path.sep) .pop();
var excludePatternMatched = excludeDirectories.filter((pattern) => {
const isMatch = typeof pattern !== 'string' && dirName.match(pattern);
if (isMatch) {
debugLogger.debug(`${dirName} matches excluded directory pattern`);
}
return isMatch;
}).length > 0;
if (!excludePatternMatched && excludeDirectories.indexOf(dirName) === -1) {
var subDirJsFilePaths = getFilePaths(directoryPath, opts);
results = results.concat(subDirJsFilePaths);
debugLogger.debug(`subDirJsFilePaths length:${results.length}`);
} else {
debugLogger.debug(`${dirName} excluded due to configured opts`);
}
});
}
return results;
};
/**
* Maps file paths of the specified `opts.extension` (default == '.js') to an object (either `opts.exports` or empty
* object that is returned). If `opts.namespaceSubdirectories`
* is true `opts.recursive` is implied true. NamespaceSubdirectories will create a hierarchy respective to the
* directory/file path. Very useful for requiring a lib folder with commonly used modules to have them all available!
* @param opts
*/
exports.mapForExports = function mapForExports(opts) {
const debugLogger = getDebug({ filePath: opts.path });
debugLogger.debug('mapForExports init');
opts.exports = opts.exports || {};
prepareOpts(opts);
opts.useNewWithExports = opts.useNewWithExports || false;
var mapResult = exports.mapPathsToObject(opts) || {};
exports.requireFiles(mapResult, opts);
return mapResult;
};
exports.requireFiles = function requireFiles(obj, opts) {
const debugLogger = getDebug({ filePath: opts.path });
debugLogger.debug('requireFiles init');
var exportsOpts = opts.exportsOpts,
recursive = typeof opts.recursive !== 'undefined' ? opts.recursive : true,
requireSiblingsBeforeRecursion = !!opts.requireSiblingsBeforeRecursion,
requireOpts = opts.requireOpts;
var libraryNames = Object.keys(obj),
recursionObjs = [],
lastRequires = [],
lastRecursionObjs = [];
for (var i= libraryNames.length; i--;) {
var name = libraryNames[i],
propertyValue = obj[name],
pushToLast = requireOpts &&
name[0] === requireOpts.prefix &&
name[0] === requireOpts.prefix && requireOpts.requireLast;
if (typeof propertyValue !== 'string') {// handle sub-object
// push off recursion until after immediate siblings are resolved
if (requireSiblingsBeforeRecursion) {
if (!pushToLast) recursionObjs.push(propertyValue); // not a last require match, but siblings come first
else lastRecursionObjs.push(propertyValue); // must require siblings & other objects before this one
}
else {
if (!pushToLast) requireFiles(propertyValue, opts); // sibling order doesn't matter, and not last require match
else lastRecursionObjs.push(propertyValue); // last require match, must require other sibling objects first
}
continue;
}
if (!pushToLast) requireFile(obj, name, propertyValue, opts);
else lastRequires.push({
name: name,
path: propertyValue
});
}
recurseObjs(recursionObjs, opts);
// Always require immediate siblings first
for(var lrIdx = lastRequires.length; lrIdx--;) {
if (!recursive) continue;
var lastRequireValues = lastRequires[lrIdx];
requireFile(obj, lastRequireValues.name, lastRequireValues.path, opts);
}
// Start recursion into last objects
recurseObjs(lastRecursionObjs, opts);
return obj;
};
function recurseObjs(objs, opts) {
var recursive = typeof opts.recursive !== 'undefined' ? opts.recursive : true;
for(var oIdx = objs.length; oIdx--;) {
if (!recursive) continue;
exports.requireFiles(objs[oIdx], opts);
}
}
function requireFile(o, name, path, opts) {
const debugLogger = getDebug({ filePath: path });
debugLogger.debug('requireFile');
var fileExports = require(path);
if (typeof fileExports !== 'function' || !opts.exportsOpts) {
o[name] = fileExports;
} else {
o[name] = opts.useNewWithExports ? new fileExports(opts.exportsOpts) : fileExports(opts.exportsOpts);
}
}
/**
* Maps file paths of the specified `opts.extension` (default == '.js') to an object. If `opts.namespaceSubdirectories`
* is true `opts.recursive` is implied true. NamespaceSubdirectories will create a hierarchy respective to the
* directory/file path. Very useful for requiring a lib folder with commonly used modules to have them all available!
* @param opts
*/
exports.mapPathsToObject = function mapPathsToObject(opts) {
const debugLogger = getDebug({ filePath: opts.path });
debugLogger.debug('mapPathsToObject init');
prepareOpts(opts);
var libraries = exports.get(opts.path, opts),
obj = opts.exports || {},
convertDashedNames = typeof opts.convertDashedNames !== 'undefined' ? opts.convertDashedNames : true;
libraries.sort(function (a, b) {
if (a < b) return -1;
if (a === b) return 0;
return 1;
}).forEach(function (library) {
var namespace = obj;
if (opts.namespaceSubdirectories) {
var namespaces = library.path.substring(library.path.indexOf(opts.path) + opts.path.length + 1);
namespaces = namespaces.split(path.sep);
namespaces.pop(); //remove filename
namespaces.forEach(function (name) {
var name = convertDashedNames ? convertDashedName(name, opts) : name;
if (!namespace[name]) {
namespace[name] = {};
}
namespace = namespace[name];
});
}
namespace[library.name] = library.path; // library name dash converted in exports.get
});
return obj;
};
function prepareOpts(opts) {
const debugLogger = getDebug({ filePath: opts.path });
debugLogger.debug('prepareOpts init');
if (!opts.path) {
throw new Error('path not specified');
}
opts.path = opts.path.replace(/(\/|\\)/gi, path.sep);
opts.path = path.resolve(opts.path);
opts.getNames = true;
opts.namespaceSubdirectories = opts.namespaceSubdirectories || false;
opts.exportsOpts = opts.exportsOpts || undefined;
if (opts.namespaceSubdirectories) {
opts.recursive = true; //implied recursion
debugLogger.debug(`opts.namespaceSubdirectories:${opts.namespaceSubdirectories} forcing implied recursion. opts.recursive:${opts.recursive}`);
}
if (opts.recursive && !opts.namespaceSubdirectories) {
debugLogger.warn('file-magik: For ', opts.path, ' recursive is true but namespaceSubdirectories is not. ' +
'Subdirectory files with same name will overwrite parents!');
}
}
function convertDashedName(name) {
var dashedIdxs = name.match(/-[a-z]/g),
camelCased = name;
if (!dashedIdxs) {
return camelCased;
}
dashedIdxs.forEach(function (match) {
camelCased = camelCased.replace(match, match.substr(-1).toUpperCase());
});
return camelCased;
}