-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
89 lines (79 loc) · 2.17 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
const { resolve } = require('path')
const pupa = require('pupa')
const series = require('promise.series')
const pathExists = require('path-exists')
const loadJsonFile = require('load-json-file')
module.exports = class UseConfig {
constructor(options = {}) {
this.options = Object.assign(
{
cwd: process.cwd(),
files: ['{name}.config.js', 'package.json']
},
options
)
this.loaders = [
{
test: /\.js$/,
loader: filepath => {
delete require.cache[filepath]
return require(filepath)
}
},
{
test: /\.json$/,
loader: filepath =>
loadJsonFile(filepath).then(json => {
if (/package\.json$/.test(filepath)) return json[this.options.name]
return json
})
}
]
}
addLoader(test, loader) {
this.loaders.push({
test,
loader
})
return this
}
load() {
if (typeof this.options.name !== 'string') {
return Promise.reject(
new TypeError('[use-config] Expect "name" to be a string')
)
}
const fallbackLoader = filepath => loadJsonFile(filepath)
return series(
this.options.files.map(_file => {
return result => {
// Pass this action when config is already retrived
if (result.path && result.config) return result
const file = pupa(_file, { name: this.options.name })
const filepath = resolve(this.options.cwd, file)
return pathExists(filepath).then(exists => {
if (!exists) return result
const loader = this.findLoader(filepath) || fallbackLoader
return Promise.resolve(loader(filepath)).then(config => {
// When config is falsy
// We think it's an invalid config file
return config
? {
path: filepath,
config
}
: {}
})
})
}
}),
{}
)
}
findLoader(filepath) {
const matched = this.loaders.filter(loader => {
return loader.test.test(filepath)
})[0]
return matched && matched.loader
}
}