forked from istanbuljs/load-nyc-config
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (77 loc) · 1.91 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
90
'use strict';
const fs = require('fs');
const path = require('path');
const camelcase = require('camelcase');
const decamelize = require('decamelize');
const findUp = require('find-up');
const standardConfigFiles = [
'.nycrc',
'.nycrc.json',
'.nycrc.yml',
'.nycrc.yaml',
'nyc.config.js'
];
function copyConfigFields(config) {
const results = {};
for (const [field, value] of Object.entries(config)) {
results[field] = value;
results[camelcase(field)] = value;
results[decamelize(field, '-')] = value;
}
return results;
}
function findPackage(options) {
const cwd = options.cwd || process.env.NYC_CWD || process.cwd();
const pkgPath = findUp.sync('package.json', {cwd});
if (pkgPath) {
return {
cwd: path.dirname(pkgPath),
pkgConfig: JSON.parse(fs.readFileSync(pkgPath, 'utf8')).nyc || {}
};
}
return {
cwd,
pkgConfig: {}
};
}
function actualLoad(configFile) {
if (!configFile) {
return {};
}
const configExt = path.extname(configFile).toLowerCase();
switch (configExt) {
case '.js':
return require(configFile);
case '.yml':
case '.yaml':
return require('js-yaml').load(
fs.readFileSync(configFile, 'utf8')
);
default:
return JSON.parse(
fs.readFileSync(configFile, 'utf8')
);
}
}
function loadNycConfig(options = {}) {
const {cwd, pkgConfig} = findPackage(options);
const configFiles = [].concat(options.nycrc || standardConfigFiles);
const configFile = findUp.sync(configFiles, {cwd});
if (options.nycrc && !configFile) {
throw new Error(`Requested configuration file ${options.nycrc} not found`);
}
const config = {
...copyConfigFields(pkgConfig),
...copyConfigFields(actualLoad(configFile))
};
const arrayFields = ['require', 'extension', 'exclude', 'include'];
for (const arrayField of arrayFields) {
if (config[arrayField]) {
config[arrayField] = [].concat(config[arrayField]);
}
}
return config;
}
module.exports = {
loadNycConfig
};