UNPKG

2.7 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.resolveConfig = resolveConfig;
7exports.resolveConfigSync = resolveConfigSync;
8exports.loadConfig = loadConfig;
9
10var _path = _interopRequireDefault(require("path"));
11
12var _clone = _interopRequireDefault(require("clone"));
13
14function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
16const PARSERS = {
17 json: require('json5').parse,
18 toml: require('@iarna/toml').parse
19};
20
21async function resolveConfig(fs, filepath, filenames, opts, root = _path.default.parse(filepath).root) {
22 filepath = await fs.realpath(_path.default.dirname(filepath)); // Don't traverse above the module root
23
24 if (_path.default.basename(filepath) === 'node_modules') {
25 return null;
26 }
27
28 for (const filename of filenames) {
29 let file = _path.default.join(filepath, filename);
30
31 if ((await fs.exists(file)) && (await fs.stat(file)).isFile()) {
32 return file;
33 }
34 }
35
36 if (filepath === root) {
37 return null;
38 }
39
40 return resolveConfig(fs, filepath, filenames, opts);
41}
42
43function resolveConfigSync(fs, filepath, filenames, opts, root = _path.default.parse(filepath).root) {
44 filepath = fs.realpathSync(_path.default.dirname(filepath)); // Don't traverse above the module root
45
46 if (filepath === root || _path.default.basename(filepath) === 'node_modules') {
47 return null;
48 }
49
50 for (const filename of filenames) {
51 let file = _path.default.join(filepath, filename);
52
53 if (fs.existsSync(file) && fs.statSync(file).isFile()) {
54 return file;
55 }
56 }
57
58 return resolveConfigSync(fs, filepath, filenames, opts);
59}
60
61async function loadConfig(fs, filepath, filenames, opts) {
62 let configFile = await resolveConfig(fs, filepath, filenames, opts);
63
64 if (configFile) {
65 try {
66 let extname = _path.default.extname(configFile).slice(1);
67
68 if (extname === 'js') {
69 return {
70 // $FlowFixMe
71 config: (0, _clone.default)(require(configFile)),
72 files: [{
73 filePath: configFile
74 }]
75 };
76 }
77
78 let configContent = await fs.readFile(configFile, 'utf8');
79
80 if (!configContent) {
81 return null;
82 }
83
84 let config;
85
86 if (opts && opts.parse === false) {
87 config = configContent;
88 } else {
89 let parse = PARSERS[extname] || PARSERS.json;
90 config = parse(configContent);
91 }
92
93 return {
94 config: config,
95 files: [{
96 filePath: configFile
97 }]
98 };
99 } catch (err) {
100 if (err.code === 'MODULE_NOT_FOUND' || err.code === 'ENOENT') {
101 return null;
102 }
103
104 throw err;
105 }
106 }
107
108 return null;
109}
\No newline at end of file