UNPKG

2.51 kBJavaScriptView Raw
1const yaml = require('js-yaml');
2const fs = require('fs');
3const pify = require('pify');
4const readPkgUp = require('read-pkg-up');
5const path = require('path');
6const stripComments = require('strip-json-comments');
7
8function processToc(config, absFilePath) {
9 if (!config || !config.toc) {
10 return config;
11 }
12
13 config.toc = config.toc.map(entry => {
14 if (entry && entry.file) {
15 entry.file = path.join(path.dirname(absFilePath), entry.file);
16 }
17
18 return entry;
19 });
20
21 return config;
22}
23
24/**
25 * Use the nearest package.json file for the default
26 * values of `name` and `version` config.
27 *
28 * @param {Object} config the user-provided config, usually via argv
29 * @returns {Promise<Object>} configuration with inferred parameters
30 * @throws {Error} if the file cannot be read.
31 */
32function mergePackage(config) {
33 if (config.noPackage) {
34 return Promise.resolve(config);
35 }
36 return (
37 readPkgUp()
38 .then(pkg => {
39 ['name', 'homepage', 'version', 'description'].forEach(key => {
40 config[`project-${key}`] = config[`project-${key}`] || pkg.pkg[key];
41 });
42 return config;
43 })
44 // Allow this to fail: this inference is not required.
45 .catch(() => config)
46 );
47}
48
49/**
50 * Merge a configuration file into program config, assuming that the location
51 * of the configuration file is given as one of those config.
52 *
53 * @param {Object} config the user-provided config, usually via argv
54 * @returns {Promise<Object>} configuration, if it can be parsed
55 * @throws {Error} if the file cannot be read.
56 */
57function mergeConfigFile(config) {
58 if (config && typeof config.config === 'string') {
59 const filePath = config.config;
60 const ext = path.extname(filePath);
61 const absFilePath = path.resolve(process.cwd(), filePath);
62 return pify(fs)
63 .readFile(absFilePath, 'utf8')
64 .then(rawFile => {
65 if (ext === '.json') {
66 return Object.assign(
67 {},
68 config,
69 processToc(JSON.parse(stripComments(rawFile)), absFilePath)
70 );
71 }
72 return Object.assign(
73 {},
74 config,
75 processToc(yaml.safeLoad(rawFile), absFilePath)
76 );
77 });
78 }
79
80 return Promise.resolve(config || {});
81}
82
83function mergeConfig(config) {
84 config.parseExtension = (config.parseExtension || []).concat([
85 'mjs',
86 'js',
87 'jsx',
88 'es5',
89 'es6',
90 'vue'
91 ]);
92
93 return mergeConfigFile(config).then(mergePackage);
94}
95
96module.exports = mergeConfig;