aboutsummaryrefslogtreecommitdiff
path: root/node_modules/cosmiconfig/lib/loadRc.js
blob: cbe1d67a8287518ed4cbf227c3becaa78f370ee6 (plain)
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
'use strict';

var yaml = require('js-yaml');
var requireFromString = require('require-from-string');
var readFile = require('./readFile');
var parseJson = require('./parseJson');

module.exports = function (filepath, options) {
  return loadExtensionlessRc().then(function (result) {
    if (result) return result;
    if (options.rcExtensions) return loadRcWithExtensions();
    return null;
  });

  function loadExtensionlessRc() {
    return readRcFile().then(function (content) {
      if (!content) return null;

      var pasedConfig = (options.rcStrictJson)
        ? parseJson(content, filepath)
        : yaml.safeLoad(content, {
          filename: filepath,
        });
      return {
        config: pasedConfig,
        filepath: filepath,
      };
    });
  }

  function loadRcWithExtensions() {
    return readRcFile('json').then(function (content) {
      if (content) {
        var successFilepath = filepath + '.json';
        return {
          config: parseJson(content, successFilepath),
          filepath: successFilepath,
        };
      }
      // If not content was found in the file with extension,
      // try the next possible extension
      return readRcFile('yaml');
    }).then(function (content) {
      if (content) {
        // If the previous check returned an object with a config
        // property, then it succeeded and this step can be skipped
        if (content.config) return content;
        // If it just returned a string, then *this* check succeeded
        var successFilepath = filepath + '.yaml';
        return {
          config: yaml.safeLoad(content, { filename: successFilepath }),
          filepath: successFilepath,
        };
      }
      return readRcFile('yml');
    }).then(function (content) {
      if (content) {
        if (content.config) return content;
        var successFilepath = filepath + '.yml';
        return {
          config: yaml.safeLoad(content, { filename: successFilepath }),
          filepath: successFilepath,
        };
      }
      return readRcFile('js');
    }).then(function (content) {
      if (content) {
        if (content.config) return content;
        var successFilepath = filepath + '.js';
        return {
          config: requireFromString(content, successFilepath),
          filepath: successFilepath,
        };
      }
      return null;
    });
  }

  function readRcFile(extension) {
    var filepathWithExtension = (extension)
      ? filepath + '.' + extension
      : filepath;
    return readFile(filepathWithExtension);
  }
};