-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
336 lines (291 loc) · 8.21 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
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
'use strict';
const fs = require('fs');
const path = require('path');
const assert = require('assert');
const Events = require('events');
const glob = require('matched');
/**
* Create an instance of `MergeConfigs` with the given `options`.
*
* ```js
* const MergeConfigs = require('merge-configs');
* const mergeConfigs = new MergeConfigs();
* ```
* @param {Object} `options`
* @return {Object} Instance of `MergeConfigs`
* @api public
*/
class MergeConfig extends Events {
constructor(config) {
super();
this.config = Object.assign({}, config);
this.defaults = { options: {}, files: [], data: {} };
if (typeof this.config.patterns === 'string') {
this.config.patterns = [this.config.patterns];
}
this.options = this.config.options || {};
this.loaders = {};
this.types = {};
if (this.options.builtinLoaders !== false) {
this.builtins();
}
}
/**
* Built-in loaders
*/
builtins() {
this.loader('json', file => JSON.parse(fs.readFileSync(file.path)));
this.loader('js', file => {
const contents = require(file.path);
delete require.cache[file.path];
return contents;
});
}
/**
* Create a new config type with the given settings
* @param {String} `type`
* @param {Object} `settings` Must have a `.patterns` property with a string or array of globs.
* @return {Object}
*/
setType(type, config) {
assert(typeof type === 'string', 'expected type to be a string');
const settings = merge({ type }, this.defaults, this.config, config);
if (typeof settings.patterns === 'string') {
settings.patterns = [settings.patterns];
}
assert(settings.patterns.length > 0, 'expected glob to be a string or array');
this.types[type] = settings;
return this;
}
/**
* Get config `type`.
* @param {String} `type`
* @return {Object}
*/
getType(type) {
assert(this.types.hasOwnProperty(type), `config type "${type}" does not exist`);
return this.types[type];
}
/**
* Set config `type` with the given `settings`, or get `type` if
* `settings` is undefined.
*
* @param {String} `type`
* @param {Object} `settings` (optional)
* @return {Object}
* @api public
*/
type(type, settings) {
assert.equal(typeof type, 'string', 'expected type to be a string');
if (typeof settings === 'undefined') {
return this.getType(type);
}
this.setType(type, settings);
return this;
}
/**
* Resolve config files for the given `type`.
*
* @param {String} `type`
* @return {Object}
* @api public
*/
resolve(type) {
assert.equal(typeof type, 'string', 'expected type to be a string');
const config = this.type(type);
const files = glob.sync(config.patterns, config.options);
const cwd = config.options.cwd || process.cwd();
const configFiles = [];
for (const filename of files) {
const filepath = path.resolve(cwd, filename);
const file = new File({ path: filepath, cwd });
if (typeof config.filter === 'function' && !config.filter(file)) {
continue;
}
configFiles.push(file);
}
this.emit('resolved', type, configFiles);
return configFiles;
}
/**
* Register a loader for a type of file, by `extname`. Loaders are functions
* that receive a [vinyl][] `file` object as the only argument and should
* return the config object to use.
*
* ```js
* // basic loader example
* config.loader('json', file => JSON.stringify(file.contents));
*
* // example of loading eslint config files
* config.loader('json', file => {
* const data = JSON.parse(file.contents);
* if (file.basename === 'package.json') {
* return data.eslintConfig;
* }
* if (file.basename === '.eslintrc.json') {
* return data;
* }
* return {};
* });
* ```
* @param {String} `extname` File extension to associate with the loader
* @param {Function} `fn` Loader function.
* @return {Object}
* @api public
*/
loader(ext, fn) {
assert.equal(typeof fn, 'function', 'expected loader to be a function');
assert.equal(typeof ext, 'string', 'expected extname to be a string');
if (ext[0] !== '.') ext = '.' + ext;
this.loaders[ext] = fn;
return this;
}
/**
* Load a single config type.
* @param {String} `type`
* @return {Object} Returns the merged config object for the type
*/
loadType(type) {
const config = this.getType(type);
const files = this.resolve(type);
config.files = files;
for (const file of files) {
const data = this.loadFile(file, config);
if (data && typeof data === 'object') {
config.data = merge({}, config.data, data);
}
}
return config;
}
/**
* Load one or more config types.
*
* @param {String|Array} `types` Loads all types if undefined.
* @return {Object} Returns the merged config object.
* @api public
*/
load(types) {
let configs = {};
if (!types) types = Object.keys(this.types);
if (typeof types === 'string') types = [types];
for (let type of types) configs[type] = this.loadType(type);
configs.merge = () => {
return types.reduce((acc, type) => merge({}, acc, configs[type].data), {});
};
return configs;
}
/**
* Load config `file`
* @param {Object} `file`
* @param {Object} `config`
* @return {Object} Returns the loaded config data.
*/
loadFile(file, config) {
let loader = this.loaders[file.extname];
assert(loader, 'no loaders are registered for: ' + file.extname);
file.data = loader.call(this, file, config);
if (typeof config.load === 'function') {
file.data = config.load.call(this, file, config);
}
return file.data;
}
/**
* Merge one or more registered config types.
*
* @param {String|Array} `types` Merges all types if undefined.
* @return {Object} Returns the merged config object.
* @api public
*/
merge(types, options, fn) {
if (typeof options === 'function') {
fn = options;
options = void 0;
}
if (!types || types === '*') types = Object.keys(this.types);
if (typeof types === 'function') return this.merge(null, types);
if (typeof fn !== 'function') fn = obj => obj.data;
if (typeof types === 'string') types = [types];
const config = this.load(types);
let res = {};
for (const type of types) {
res = merge({}, res, fn(config[type]));
}
return options ? merge({}, options, res) : res;
}
}
class File {
constructor(file) {
this.path = file.path;
this.cwd = file.cwd;
}
get dirname() {
return path.dirname(this.path);
}
get basename() {
return path.basename(this.path);
}
get stem() {
return path.basename(this.path, this.extname);
}
get extname() {
return path.extname(this.path);
}
}
function merge(target, ...rest) {
let orig = clone(target);
for (let obj of rest) {
if (isObject(obj) || Array.isArray(obj)) {
for (let key of Object.keys(obj)) {
if (key !== '__proto__' && key !== 'constructor') {
mixin(orig, obj[key], key);
}
}
}
}
return orig;
}
function mixin(target, val, key) {
let orig = target[key];
if (isObject(val) && isObject(orig)) {
target[key] = merge(orig, val);
} else if (Array.isArray(val)) {
target[key] = union([], orig, val);
} else {
target[key] = clone(val);
}
return target;
}
function union(...args) {
return [...new Set([].concat.apply([], args).filter(Boolean))];
}
function clone(value) {
let obj = {};
switch (typeOf(value)) {
case 'array':
return value.map(clone);
case 'object':
for (let key of Object.keys(value)) {
obj[key] = clone(value[key]);
}
return obj;
default: {
return value;
}
}
}
function typeOf(val) {
if (val === null) return 'null';
if (val === void 0) return 'undefiend';
if (val instanceof RegExp) return 'regexp';
if (typeof val === 'number') return 'number';
if (typeof val === 'string') return 'string';
if (Array.isArray(val)) return 'array';
return typeof val;
}
function isObject(val) {
return (typeof val === 'object' && val !== null && !Array.isArray(val));
}
/**
* Expose `MergeConfig`
*/
module.exports = MergeConfig;