Initial commit
[yaffs-website] / node_modules / cosmiconfig / lib / loadRc.js
1 'use strict';
2
3 var yaml = require('js-yaml');
4 var parseJson = require('parse-json');
5 var requireFromString = require('require-from-string');
6 var readFile = require('./readFile');
7
8 module.exports = function (filepath, options) {
9   return loadExtensionlessRc().then(function (result) {
10     if (result) return result;
11     if (options.rcExtensions) return loadRcWithExtensions();
12     return null;
13   });
14
15   function loadExtensionlessRc() {
16     return readRcFile().then(function (content) {
17       if (!content) return null;
18
19       var pasedConfig = (options.rcStrictJson)
20         ? parseJson(content, filepath)
21         : yaml.safeLoad(content, {
22           filename: filepath,
23         });
24       return {
25         config: pasedConfig,
26         filepath: filepath,
27       };
28     });
29   }
30
31   function loadRcWithExtensions() {
32     return readRcFile('json').then(function (content) {
33       if (content) {
34         var successFilepath = filepath + '.json';
35         return {
36           config: parseJson(content, successFilepath),
37           filepath: successFilepath,
38         };
39       }
40       // If not content was found in the file with extension,
41       // try the next possible extension
42       return readRcFile('yaml');
43     }).then(function (content) {
44       if (content) {
45         // If the previous check returned an object with a config
46         // property, then it succeeded and this step can be skipped
47         if (content.config) return content;
48         // If it just returned a string, then *this* check succeeded
49         var successFilepath = filepath + '.yaml';
50         return {
51           config: yaml.safeLoad(content, { filename: successFilepath }),
52           filepath: successFilepath,
53         };
54       }
55       return readRcFile('yml');
56     }).then(function (content) {
57       if (content) {
58         if (content.config) return content;
59         var successFilepath = filepath + '.yml';
60         return {
61           config: yaml.safeLoad(content, { filename: successFilepath }),
62           filepath: successFilepath,
63         };
64       }
65       return readRcFile('js');
66     }).then(function (content) {
67       if (content) {
68         if (content.config) return content;
69         var successFilepath = filepath + '.js';
70         return {
71           config: requireFromString(content, successFilepath),
72           filepath: successFilepath,
73         };
74       }
75       return null;
76     });
77   }
78
79   function readRcFile(extension) {
80     var filepathWithExtension = (extension)
81       ? filepath + '.' + extension
82       : filepath;
83     return readFile(filepathWithExtension);
84   }
85 };