You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.9 KiB

4 years ago
  1. //
  2. 'use strict';
  3. const os = require('os');
  4. const createExplorer = require('./createExplorer');
  5. const loaders = require('./loaders');
  6. module.exports = cosmiconfig;
  7. function cosmiconfig(
  8. moduleName ,
  9. options
  10. ) {
  11. options = options || {};
  12. const defaults = {
  13. packageProp: moduleName,
  14. searchPlaces: [
  15. 'package.json',
  16. `.${moduleName}rc`,
  17. `.${moduleName}rc.json`,
  18. `.${moduleName}rc.yaml`,
  19. `.${moduleName}rc.yml`,
  20. `.${moduleName}rc.js`,
  21. `${moduleName}.config.js`,
  22. ],
  23. ignoreEmptySearchPlaces: true,
  24. stopDir: os.homedir(),
  25. cache: true,
  26. transform: identity,
  27. };
  28. const normalizedOptions = Object.assign(
  29. {},
  30. defaults,
  31. options,
  32. {
  33. loaders: normalizeLoaders(options.loaders),
  34. }
  35. );
  36. return createExplorer(normalizedOptions);
  37. }
  38. cosmiconfig.loadJs = loaders.loadJs;
  39. cosmiconfig.loadJson = loaders.loadJson;
  40. cosmiconfig.loadYaml = loaders.loadYaml;
  41. function normalizeLoaders(rawLoaders ) {
  42. const defaults = {
  43. '.js': { sync: loaders.loadJs, async: loaders.loadJs },
  44. '.json': { sync: loaders.loadJson, async: loaders.loadJson },
  45. '.yaml': { sync: loaders.loadYaml, async: loaders.loadYaml },
  46. '.yml': { sync: loaders.loadYaml, async: loaders.loadYaml },
  47. noExt: { sync: loaders.loadYaml, async: loaders.loadYaml },
  48. };
  49. if (!rawLoaders) {
  50. return defaults;
  51. }
  52. return Object.keys(rawLoaders).reduce((result, ext) => {
  53. const entry = rawLoaders && rawLoaders[ext];
  54. if (typeof entry === 'function') {
  55. result[ext] = { sync: entry, async: entry };
  56. } else {
  57. result[ext] = entry;
  58. }
  59. return result;
  60. }, defaults);
  61. }
  62. function identity(x) {
  63. return x;
  64. }