1
0
mirror of https://github.com/thangisme/notes.git synced 2024-11-01 06:37:17 -04:00
notes/node_modules/cosmiconfig/lib/loadDefinedFile.js

67 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-03-09 13:16:08 -05:00
'use strict';
var yaml = require('js-yaml');
var parseJson = require('parse-json');
var requireFromString = require('require-from-string');
var readFile = require('./readFile');
module.exports = function (filepath, options) {
return readFile(filepath, { throwNotFound: true }).then(function (content) {
var parsedConfig = (function () {
switch (options.format) {
case 'json':
return parseJson(content, filepath);
case 'yaml':
return yaml.safeLoad(content, {
filename: filepath,
});
case 'js':
return requireFromString(content, filepath);
default:
return tryAllParsing(content, filepath);
}
})();
if (!parsedConfig) {
throw new Error(
'Failed to parse "' + filepath + '" as JSON, JS, or YAML.'
);
}
return {
config: parsedConfig,
filepath: filepath,
};
});
};
function tryAllParsing(content, filepath) {
return tryYaml(content, filepath, function () {
return tryRequire(content, filepath, function () {
return null;
});
});
}
function tryYaml(content, filepath, cb) {
try {
var result = yaml.safeLoad(content, {
filename: filepath,
});
if (typeof result === 'string') {
return cb();
}
return result;
} catch (e) {
return cb();
}
}
function tryRequire(content, filepath, cb) {
try {
return requireFromString(content, filepath);
} catch (e) {
return cb();
}
}