createExplorer.js
9.39 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
//
'use strict';
const path = require('path');
const loaders = require('./loaders');
const readFile = require('./readFile');
const cacheWrapper = require('./cacheWrapper');
const getDirectory = require('./getDirectory');
const getPropertyByPath = require('./getPropertyByPath');
const MODE_SYNC = 'sync';
// An object value represents a config object.
// null represents that the loader did not find anything relevant.
// undefined represents that the loader found something relevant
// but it was empty.
class Explorer {
constructor(options ) {
this.loadCache = options.cache ? new Map() : null;
this.loadSyncCache = options.cache ? new Map() : null;
this.searchCache = options.cache ? new Map() : null;
this.searchSyncCache = options.cache ? new Map() : null;
this.config = options;
this.validateConfig();
}
clearLoadCache() {
if (this.loadCache) {
this.loadCache.clear();
}
if (this.loadSyncCache) {
this.loadSyncCache.clear();
}
}
clearSearchCache() {
if (this.searchCache) {
this.searchCache.clear();
}
if (this.searchSyncCache) {
this.searchSyncCache.clear();
}
}
clearCaches() {
this.clearLoadCache();
this.clearSearchCache();
}
validateConfig() {
const config = this.config;
config.searchPlaces.forEach(place => {
const loaderKey = path.extname(place) || 'noExt';
const loader = config.loaders[loaderKey];
if (!loader) {
throw new Error(
`No loader specified for ${getExtensionDescription(
place
)}, so searchPlaces item "${place}" is invalid`
);
}
});
}
search(searchFrom ) {
searchFrom = searchFrom || process.cwd();
return getDirectory(searchFrom).then(dir => {
return this.searchFromDirectory(dir);
});
}
searchFromDirectory(dir ) {
const absoluteDir = path.resolve(process.cwd(), dir);
const run = () => {
return this.searchDirectory(absoluteDir).then(result => {
const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
if (nextDir) {
return this.searchFromDirectory(nextDir);
}
return this.config.transform(result);
});
};
if (this.searchCache) {
return cacheWrapper(this.searchCache, absoluteDir, run);
}
return run();
}
searchSync(searchFrom ) {
searchFrom = searchFrom || process.cwd();
const dir = getDirectory.sync(searchFrom);
return this.searchFromDirectorySync(dir);
}
searchFromDirectorySync(dir ) {
const absoluteDir = path.resolve(process.cwd(), dir);
const run = () => {
const result = this.searchDirectorySync(absoluteDir);
const nextDir = this.nextDirectoryToSearch(absoluteDir, result);
if (nextDir) {
return this.searchFromDirectorySync(nextDir);
}
return this.config.transform(result);
};
if (this.searchSyncCache) {
return cacheWrapper(this.searchSyncCache, absoluteDir, run);
}
return run();
}
searchDirectory(dir ) {
return this.config.searchPlaces.reduce((prevResultPromise, place) => {
return prevResultPromise.then(prevResult => {
if (this.shouldSearchStopWithResult(prevResult)) {
return prevResult;
}
return this.loadSearchPlace(dir, place);
});
}, Promise.resolve(null));
}
searchDirectorySync(dir ) {
let result = null;
for (const place of this.config.searchPlaces) {
result = this.loadSearchPlaceSync(dir, place);
if (this.shouldSearchStopWithResult(result)) break;
}
return result;
}
shouldSearchStopWithResult(result ) {
if (result === null) return false;
if (result.isEmpty && this.config.ignoreEmptySearchPlaces) return false;
return true;
}
loadSearchPlace(dir , place ) {
const filepath = path.join(dir, place);
return readFile(filepath).then(content => {
return this.createCosmiconfigResult(filepath, content);
});
}
loadSearchPlaceSync(dir , place ) {
const filepath = path.join(dir, place);
const content = readFile.sync(filepath);
return this.createCosmiconfigResultSync(filepath, content);
}
nextDirectoryToSearch(
currentDir ,
currentResult
) {
if (this.shouldSearchStopWithResult(currentResult)) {
return null;
}
const nextDir = nextDirUp(currentDir);
if (nextDir === currentDir || currentDir === this.config.stopDir) {
return null;
}
return nextDir;
}
loadPackageProp(filepath , content ) {
const parsedContent = loaders.loadJson(filepath, content);
const packagePropValue = getPropertyByPath(
parsedContent,
this.config.packageProp
);
return packagePropValue || null;
}
getLoaderEntryForFile(filepath ) {
if (path.basename(filepath) === 'package.json') {
const loader = this.loadPackageProp.bind(this);
return { sync: loader, async: loader };
}
const loaderKey = path.extname(filepath) || 'noExt';
return this.config.loaders[loaderKey] || {};
}
getSyncLoaderForFile(filepath ) {
const entry = this.getLoaderEntryForFile(filepath);
if (!entry.sync) {
throw new Error(
`No sync loader specified for ${getExtensionDescription(filepath)}`
);
}
return entry.sync;
}
getAsyncLoaderForFile(filepath ) {
const entry = this.getLoaderEntryForFile(filepath);
const loader = entry.async || entry.sync;
if (!loader) {
throw new Error(
`No async loader specified for ${getExtensionDescription(filepath)}`
);
}
return loader;
}
loadFileContent(
mode ,
filepath ,
content
) {
if (content === null) {
return null;
}
if (content.trim() === '') {
return undefined;
}
const loader =
mode === MODE_SYNC
? this.getSyncLoaderForFile(filepath)
: this.getAsyncLoaderForFile(filepath);
return loader(filepath, content);
}
loadedContentToCosmiconfigResult(
filepath ,
loadedContent
) {
if (loadedContent === null) {
return null;
}
if (loadedContent === undefined) {
return { filepath, config: undefined, isEmpty: true };
}
return { config: loadedContent, filepath };
}
createCosmiconfigResult(
filepath ,
content
) {
return Promise.resolve()
.then(() => {
return this.loadFileContent('async', filepath, content);
})
.then(loaderResult => {
return this.loadedContentToCosmiconfigResult(filepath, loaderResult);
});
}
createCosmiconfigResultSync(
filepath ,
content
) {
const loaderResult = this.loadFileContent('sync', filepath, content);
return this.loadedContentToCosmiconfigResult(filepath, loaderResult);
}
validateFilePath(filepath ) {
if (!filepath) {
throw new Error('load and loadSync must pass a non-empty string');
}
}
load(filepath ) {
return Promise.resolve().then(() => {
this.validateFilePath(filepath);
const absoluteFilePath = path.resolve(process.cwd(), filepath);
return cacheWrapper(this.loadCache, absoluteFilePath, () => {
return readFile(absoluteFilePath, { throwNotFound: true })
.then(content => {
return this.createCosmiconfigResult(absoluteFilePath, content);
})
.then(this.config.transform);
});
});
}
loadSync(filepath ) {
this.validateFilePath(filepath);
const absoluteFilePath = path.resolve(process.cwd(), filepath);
return cacheWrapper(this.loadSyncCache, absoluteFilePath, () => {
const content = readFile.sync(absoluteFilePath, { throwNotFound: true });
const result = this.createCosmiconfigResultSync(
absoluteFilePath,
content
);
return this.config.transform(result);
});
}
}
module.exports = function createExplorer(options ) {
const explorer = new Explorer(options);
return {
search: explorer.search.bind(explorer),
searchSync: explorer.searchSync.bind(explorer),
load: explorer.load.bind(explorer),
loadSync: explorer.loadSync.bind(explorer),
clearLoadCache: explorer.clearLoadCache.bind(explorer),
clearSearchCache: explorer.clearSearchCache.bind(explorer),
clearCaches: explorer.clearCaches.bind(explorer),
};
};
function nextDirUp(dir ) {
return path.dirname(dir);
}
function getExtensionDescription(filepath ) {
const ext = path.extname(filepath);
return ext ? `extension "${ext}"` : 'files without extensions';
}