Initial commit
[yaffs-website] / node_modules / cosmiconfig / lib / loadDefinedFile.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 readFile(filepath, { throwNotFound: true }).then(function (content) {
10     var parsedConfig = (function () {
11       switch (options.format) {
12         case 'json':
13           return parseJson(content, filepath);
14         case 'yaml':
15           return yaml.safeLoad(content, {
16             filename: filepath,
17           });
18         case 'js':
19           return requireFromString(content, filepath);
20         default:
21           return tryAllParsing(content, filepath);
22       }
23     })();
24
25     if (!parsedConfig) {
26       throw new Error(
27         'Failed to parse "' + filepath + '" as JSON, JS, or YAML.'
28       );
29     }
30
31     return {
32       config: parsedConfig,
33       filepath: filepath,
34     };
35   });
36 };
37
38 function tryAllParsing(content, filepath) {
39   return tryYaml(content, filepath, function () {
40     return tryRequire(content, filepath, function () {
41       return null;
42     });
43   });
44 }
45
46 function tryYaml(content, filepath, cb) {
47   try {
48     var result = yaml.safeLoad(content, {
49       filename: filepath,
50     });
51     if (typeof result === 'string') {
52       return cb();
53     }
54     return result;
55   } catch (e) {
56     return cb();
57   }
58 }
59
60 function tryRequire(content, filepath, cb) {
61   try {
62     return requireFromString(content, filepath);
63   } catch (e) {
64     return cb();
65   }
66 }