forked from documentationjs/documentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_config.js
96 lines (86 loc) · 2.45 KB
/
merge_config.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
const yaml = require('js-yaml');
const fs = require('fs');
const pify = require('pify');
const readPkgUp = require('read-pkg-up');
const path = require('path');
const stripComments = require('strip-json-comments');
function processToc(config, absFilePath) {
if (!config || !config.toc) {
return config;
}
config.toc = config.toc.map(entry => {
if (entry && entry.file) {
entry.file = path.join(path.dirname(absFilePath), entry.file);
}
return entry;
});
return config;
}
/**
* Use the nearest package.json file for the default
* values of `name` and `version` config.
*
* @param {Object} config the user-provided config, usually via argv
* @returns {Promise<Object>} configuration with inferred parameters
* @throws {Error} if the file cannot be read.
*/
function mergePackage(config) {
if (config.noPackage) {
return Promise.resolve(config);
}
return (
readPkgUp()
.then(pkg => {
['name', 'homepage', 'version', 'description'].forEach(key => {
config[`project-${key}`] = config[`project-${key}`] || pkg.pkg[key];
});
return config;
})
// Allow this to fail: this inference is not required.
.catch(() => config)
);
}
/**
* Merge a configuration file into program config, assuming that the location
* of the configuration file is given as one of those config.
*
* @param {Object} config the user-provided config, usually via argv
* @returns {Promise<Object>} configuration, if it can be parsed
* @throws {Error} if the file cannot be read.
*/
function mergeConfigFile(config) {
if (config && typeof config.config === 'string') {
const filePath = config.config;
const ext = path.extname(filePath);
const absFilePath = path.resolve(process.cwd(), filePath);
return pify(fs)
.readFile(absFilePath, 'utf8')
.then(rawFile => {
if (ext === '.json') {
return Object.assign(
{},
config,
processToc(JSON.parse(stripComments(rawFile)), absFilePath)
);
}
return Object.assign(
{},
config,
processToc(yaml.safeLoad(rawFile), absFilePath)
);
});
}
return Promise.resolve(config || {});
}
function mergeConfig(config) {
config.parseExtension = (config.parseExtension || []).concat([
'mjs',
'js',
'jsx',
'es5',
'es6',
'vue'
]);
return mergeConfigFile(config).then(mergePackage);
}
module.exports = mergeConfig;