This repository was archived by the owner on Oct 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
336 lines (268 loc) · 11 KB
/
index.js
File metadata and controls
336 lines (268 loc) · 11 KB
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
var readdirr = require('readdir-recursive');
var globule = require('globule');
var helpers = require('./src/helpers');
var s = require('./src/string');
var parser = require('./src/parser');
// {File path -> meta} mapping
var meta = {};
// {Provider -> [file]} mapping for fast lookup
var providerCache = {};
// {Module name -> file[]} mapping for fast lookup
var moduleCache = {};
// Shared options
var options = {};
var illegalPathCharRegexp = /<>:\?\*/;
var externalModulesRegexp = /bower_components|node_modules/i;
module.exports = {
_parse: function (file) {
if (file in meta) {
// Skip if not modified
var stat = fs.lstatSync(file);
if (+stat.mtime < meta[file].lastUpdated) {
meta[file].lastUpdated = +new Date();
return false;
}
}
var content = fs.readFileSync(file).toString();
try {
var metaData = parser.parse(content, options);
if (metaData === undefined) {
// Not a angular module never check again
meta[file] = { path: file, angular: false, lastUpdated: +new Date() };
} else {
// Add to registry
meta[file] = _.extend({ path: file, angular: true, lastUpdated: +new Date() }, metaData);
}
return meta[file];
} catch (e) {
e.message = 'Error in parsing file {0}. {1}'.f(file, e.message);
throw e;
}
},
/**
* Update the mapping: moduleName -> filePath
*
* @param files Array of file paths or file content
*/
_update: function (files) {
var self = this;
var skipped = [], success = [];
if (!Array.isArray(files)) {
files = [ files ];
}
// Expand folders
for (var i = files.length -1 ; i >= 0; i--) {
var file = files[i];
if (!fs.existsSync(file)) {
throw new Error('Can not find file {0}'.f(file));
}
var stat = fs.lstatSync(file);
if (stat.isDirectory()) {
// Remove the folder
files.splice(i, 1);
// Push files
files = files.concat(readdirr.fileSync(file));
}
}
_.each(files, function (file) {
// Parse the file
var metaData = self._parse(file);
if (metaData === false || !metaData.angular) {
return skipped.push(file);
}
var moduleName = metaData.moduleName;
// Do not apply naming check on external modules
if (!externalModulesRegexp.test(file)) {
// Naming check
if (options.ensureModuleName) {
var expectedModuleName = path.dirname(file).replace(/\//g, '.');
if (!s.nullOrEmpty(moduleName) && expectedModuleName.indexOf(moduleName) === -1) {
throw new Error('Module "{0}" should follow folder path for {1}'.f(moduleName, file));
}
}
if (options.ensureProviderName) {
if (metaData.namedProviders.length > 1) {
throw new Error('Please define named providers "{0}" in different files'.f(metaData.namedProviders.join(', ')));
} else if (metaData.namedProviders.length === 1 && !s.nullOrEmpty(metaData.namedProviders[0])) {
var baseName = path.basename(file, '.js');
var providerName = metaData.namedProviders[0].toLowerCase().replace(/[\-_]+/g, '');
var expectedProviderNames = [];
// like example
expectedProviderNames.push(baseName.toLowerCase());
// like ExampleController
expectedProviderNames.push((baseName + metaData.providerTypes[0]).toLowerCase());
// also skip ones start with $
if (providerName[0] !== '$' && expectedProviderNames.indexOf(providerName) === -1) {
throw new Error('Provider "{0}" is not matching file name at {1}'.f(metaData.namedProviders[0], file));
}
}
}
}
// Add to cache
moduleCache[moduleName] = _.union(moduleCache[moduleName] || [], [ file ]);
_.each(metaData.namedProviders, function (namedProvider) {
providerCache[namedProvider] = providerCache[namedProvider] || [];
providerCache[namedProvider].push(file);
});
success.push(file);
});
return {
success: success,
skipped: skipped
}
},
/**
* Get META data from absolute file path
* Please do a update before calling this to ensure latest status
*
* @param file
* @returns Object
*/
getMeta: function (file) {
return s.nullOrEmpty(file) ? meta : meta[file];
},
/**
* Get modules that not included
*
* @param file
* @return {Object}
*/
getMissingDependencies: function (file) {
var self = this;
if (!(file in meta)) {
self._update(file);
}
var fileMeta = meta[file];
var fileBase = path.dirname(file);
var result = [], loadedModules = {}, loadedProviders = {};
// Add loaded providers to the list
_.map(fileMeta.loadedFiles, function (relativePath) {
// Check if the path is actually path
// Webpack may have many fancy stuff like require('bundle?a')
if (!relativePath || illegalPathCharRegexp.test(relativePath) || !relativePath.startsWith('.')) {
return;
}
var filePath = path.resolve(fileBase, relativePath);
// Default to js
if (s.nullOrEmpty(path.extname(filePath))) {
filePath += '.js';
}
/*
* To be a valid provider:
* File path is in the registry and also in the dependency list
* Or the file path is not in registry but the parse result indicates it's a angular module
*/
var loadedFileMeta;
/*
* Best effort to parse required file
*/
if (!(filePath in meta) && path.extname(filePath) === '.js' && fs.existsSync(filePath)) {
// attempt to parse file
self._parse(filePath);
}
loadedFileMeta = meta[filePath];
if (loadedFileMeta) {
var isDependency = fileMeta.dependencies.indexOf(loadedFileMeta.moduleName) !== -1;
var isInSameModule = fileMeta.moduleName === loadedFileMeta.moduleName;
// A provider can be regarded as loaded only if
// - Being required (require('path'))
// - Have dependency on angular.module('name', [ dependency here ])
if (isInSameModule || isDependency) {
loadedProviders[loadedFileMeta.namedProviders] = true;
}
loadedModules[loadedFileMeta.moduleName] = true;
}
});
// Find out what is missing
var missingInjectedProviders = _.difference(fileMeta.injectedProviders, _.keys(loadedProviders));
// Try to find them in the cache
for (var i = missingInjectedProviders.length - 1; i >= 0; i--) {
var provider = missingInjectedProviders[i];
if (provider in providerCache) {
missingInjectedProviders.splice(i, 1);
// Absolute to relative path
var absolutePaths = providerCache[provider];
var availableChoices = _.transform(absolutePaths, function (result, absolutePath) {
result.push({
path: absolutePath,
relativePath: helpers.absolutePathToRelative(fileBase, absolutePath)
});
});
// Sort relative path from shortest to longest
availableChoices.sort(function (pathA, pathB) {
return pathA.relativePath.length - pathB.relativePath.length;
});
var choice = availableChoices[0];
// Use the shortest one
result.push({
providerName: provider,
moduleName: meta[choice.path].moduleName,
path: choice.path,
relativePath: choice.relativePath
});
}
}
// If still can't find
if (options.ignoreProviders && options.ignoreProviders.length > 0) {
missingInjectedProviders = _.filter(missingInjectedProviders, function (missingInjectedProvider) {
var ignore = false;
_.each(options.ignoreProviders, function (ignoreExpr) {
if (helpers.isString(ignoreExpr)) {
ignore = ignoreExpr === missingInjectedProvider;
}
if (helpers.isRegexp(ignoreExpr)) {
ignore = ignoreExpr.test(missingInjectedProvider);
}
if (ignore) return false;
});
return !ignore;
});
}
if (missingInjectedProviders.length > 0) {
throw new Error('Can not find provider "{0}" in {1}'.f(missingInjectedProviders.join(', '), file));
}
// Include modules that user explicit specified
_.each(fileMeta.dependencies, function (dependency) {
if (!(dependency in loadedModules)) {
// Absolute to relative path
var absolutePaths = moduleCache[dependency];
// Only process known modules
if (absolutePaths) {
_.each(absolutePaths, function (absolutePath) {
var relativePath = helpers.absolutePathToRelative(fileBase, absolutePath);
result.push({
providerName: '',
moduleName: dependency,
path: absolutePath,
relativePath: relativePath
});
});
}
}
});
return result;
},
/**
* Update the mapping: moduleName -> filePath
*
* @param patterns
* @param updateOptions
*/
update: function (patterns, updateOptions) {
var self = this;
var paths = globule.find(patterns);
options = _.extend(options, updateOptions);
return self._update(paths);
},
/**
* Clean cache
*/
clean: function () {
meta = {};
options = {};
providerCache = {};
}
};