UNPKG

3.16 kBJavaScriptView Raw
1//
2'use strict';
3
4const yaml = require('js-yaml');
5const requireFromString = require('require-from-string');
6const readFile = require('./readFile');
7const parseJson = require('./parseJson');
8const funcRunner = require('./funcRunner');
9
10module.exports = function loadRc(
11 filepath ,
12 options
13
14
15
16
17) {
18 if (!options.sync) {
19 return readFile(filepath)
20 .then(parseExtensionlessRcFile)
21 .then(checkExtensionlessRcResult);
22 } else {
23 return checkExtensionlessRcResult(
24 parseExtensionlessRcFile(readFile.sync(filepath))
25 );
26 }
27
28 function checkExtensionlessRcResult(result) {
29 if (result) return result;
30 if (options.rcExtensions) return loadRcWithExtensions();
31 return null;
32 }
33
34 function parseExtensionlessRcFile(content ) {
35 if (!content) return null;
36 const pasedConfig = options.rcStrictJson
37 ? parseJson(content, filepath)
38 : yaml.safeLoad(content, { filename: filepath });
39 return {
40 config: pasedConfig,
41 filepath,
42 };
43 }
44
45 function loadRcWithExtensions() {
46 let foundConfig = null;
47 return funcRunner(readRcFile('json'), [
48 (jsonContent ) => {
49 // Since this is the first try, config cannot have been found, so don't
50 // check `if (foundConfig)`.
51 if (jsonContent) {
52 const successFilepath = `${filepath}.json`;
53 foundConfig = {
54 config: parseJson(jsonContent, successFilepath),
55 filepath: successFilepath,
56 };
57 } else {
58 return readRcFile('yaml');
59 }
60 },
61 (yamlContent ) => {
62 if (foundConfig) {
63 return;
64 } else if (yamlContent) {
65 const successFilepath = `${filepath}.yaml`;
66 foundConfig = {
67 config: yaml.safeLoad(yamlContent, { filename: successFilepath }),
68 filepath: successFilepath,
69 };
70 } else {
71 return readRcFile('yml');
72 }
73 },
74 (ymlContent ) => {
75 if (foundConfig) {
76 return;
77 } else if (ymlContent) {
78 const successFilepath = `${filepath}.yml`;
79 foundConfig = {
80 config: yaml.safeLoad(ymlContent, { filename: successFilepath }),
81 filepath: successFilepath,
82 };
83 } else {
84 return readRcFile('js');
85 }
86 },
87 (jsContent ) => {
88 if (foundConfig) {
89 return;
90 } else if (jsContent) {
91 const successFilepath = `${filepath}.js`;
92 foundConfig = {
93 config: requireFromString(jsContent, successFilepath),
94 filepath: successFilepath,
95 };
96 } else {
97 return;
98 }
99 },
100 () => foundConfig,
101 ]);
102 }
103
104 function readRcFile(extension ) {
105 const filepathWithExtension = `${filepath}.${extension}`;
106 return !options.sync
107 ? readFile(filepathWithExtension)
108 : readFile.sync(filepathWithExtension);
109 }
110};