forked from styleguidist/react-styleguidist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.js
79 lines (67 loc) · 1.86 KB
/
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
'use strict';
const fs = require('fs');
const path = require('path');
const findup = require('findup');
const isString = require('lodash/isString');
const merge = require('lodash/merge');
const StyleguidistError = require('./utils/error');
const sanitizeConfig = require('./utils/sanitizeConfig');
const schema = require('./schemas/config');
const CONFIG_FILENAME = 'styleguide.config.js';
/**
* Read, parse and validate config file or passed config.
*
* @param {object|string} [config] All config options or config file name or nothing.
* @returns {object}
*/
function getConfig(config) {
config = config || {};
let configFilepath;
if (isString(config)) {
// Load config from a given file
configFilepath = path.resolve(process.cwd(), config);
if (!fs.existsSync(configFilepath)) {
throw new StyleguidistError('Styleguidist config not found: ' + configFilepath + '.');
}
config = {};
} else {
// Try to read config options from a file
configFilepath = findConfigFile();
}
if (configFilepath) {
config = require(configFilepath);
}
const configDir = configFilepath ? path.dirname(configFilepath) : process.cwd();
let sanitizedConfig;
try {
sanitizedConfig = sanitizeConfig(config, schema, configDir);
} catch (exception) {
if (exception instanceof StyleguidistError) {
throw new StyleguidistError(
'Something is wrong with your style guide config',
exception.message
);
} else {
throw exception;
}
}
const mergedConfig = merge({}, sanitizedConfig, {
configDir,
});
return mergedConfig;
}
/**
* Try to find config file up the file tree.
*
* @return {string|boolean} Config absolute file path.
*/
function findConfigFile() {
let configDir;
try {
configDir = findup.sync(process.cwd(), CONFIG_FILENAME);
} catch (exception) {
return false;
}
return path.join(configDir, CONFIG_FILENAME);
}
module.exports = getConfig;