1 |
|
2 | 'use strict';
|
3 |
|
4 | const yaml = require('js-yaml');
|
5 | const requireFromString = require('require-from-string');
|
6 | const readFile = require('./readFile');
|
7 | const parseJson = require('./parseJson');
|
8 |
|
9 | module.exports = function loadDefinedFile(
|
10 | filepath ,
|
11 | options
|
12 |
|
13 |
|
14 |
|
15 | ) {
|
16 | function parseContent(content ) {
|
17 | if (!content) {
|
18 | throw new Error(`Config file is empty! Filepath - "${filepath}".`);
|
19 | }
|
20 |
|
21 | let parsedConfig;
|
22 | switch (options.format) {
|
23 | case 'json':
|
24 | parsedConfig = parseJson(content, filepath);
|
25 | break;
|
26 | case 'yaml':
|
27 | parsedConfig = yaml.safeLoad(content, {
|
28 | filename: filepath,
|
29 | });
|
30 | break;
|
31 | case 'js':
|
32 | parsedConfig = requireFromString(content, filepath);
|
33 | break;
|
34 | default:
|
35 | parsedConfig = tryAllParsing(content, filepath);
|
36 | }
|
37 |
|
38 | if (!parsedConfig) {
|
39 | throw new Error(`Failed to parse "${filepath}" as JSON, JS, or YAML.`);
|
40 | }
|
41 |
|
42 | return {
|
43 | config: parsedConfig,
|
44 | filepath,
|
45 | };
|
46 | }
|
47 |
|
48 | return !options.sync
|
49 | ? readFile(filepath, { throwNotFound: true }).then(parseContent)
|
50 | : parseContent(readFile.sync(filepath, { throwNotFound: true }));
|
51 | };
|
52 |
|
53 | function tryAllParsing(content , filepath ) {
|
54 | return tryYaml(content, filepath, () => {
|
55 | return tryRequire(content, filepath, () => {
|
56 | return null;
|
57 | });
|
58 | });
|
59 | }
|
60 |
|
61 | function tryYaml(content , filepath , cb ) {
|
62 | try {
|
63 | const result = yaml.safeLoad(content, {
|
64 | filename: filepath,
|
65 | });
|
66 | if (typeof result === 'string') {
|
67 | return cb();
|
68 | }
|
69 | return result;
|
70 | } catch (e) {
|
71 | return cb();
|
72 | }
|
73 | }
|
74 |
|
75 | function tryRequire(content , filepath , cb ) {
|
76 | try {
|
77 | return requireFromString(content, filepath);
|
78 | } catch (e) {
|
79 | return cb();
|
80 | }
|
81 | }
|