1 | const yaml = require('js-yaml');
|
2 | const fs = require('fs');
|
3 | const pify = require('pify');
|
4 | const readPkgUp = require('read-pkg-up');
|
5 | const path = require('path');
|
6 | const stripComments = require('strip-json-comments');
|
7 |
|
8 | function 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 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 | function 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 |
|
45 | .catch(() => config)
|
46 | );
|
47 | }
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 | function 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 |
|
83 | function 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 |
|
96 | module.exports = mergeConfig;
|