loadRc.js 2.5 KB

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