config.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. /**
  3. * Responsible for loading / finding Mocha's "rc" files.
  4. * This doesn't have anything to do with `mocha.opts`.
  5. *
  6. * @private
  7. * @module
  8. */
  9. const fs = require('fs');
  10. const findUp = require('findup-sync');
  11. const path = require('path');
  12. const debug = require('debug')('mocha:cli:config');
  13. /**
  14. * These are the valid config files, in order of precedence;
  15. * e.g., if `.mocharc.js` is present, then `.mocharc.yaml` and the rest
  16. * will be ignored.
  17. * The user should still be able to explicitly specify a file.
  18. * @private
  19. */
  20. exports.CONFIG_FILES = [
  21. '.mocharc.js',
  22. '.mocharc.yaml',
  23. '.mocharc.yml',
  24. '.mocharc.json'
  25. ];
  26. /**
  27. * Parsers for various config filetypes. Each accepts a filepath and
  28. * returns an object (but could throw)
  29. */
  30. const parsers = (exports.parsers = {
  31. yaml: filepath =>
  32. require('js-yaml').safeLoad(fs.readFileSync(filepath, 'utf8')),
  33. js: filepath => require(filepath),
  34. json: filepath =>
  35. JSON.parse(
  36. require('strip-json-comments')(fs.readFileSync(filepath, 'utf8'))
  37. )
  38. });
  39. /**
  40. * Loads and parses, based on file extension, a config file.
  41. * "JSON" files may have comments.
  42. * @param {string} filepath - Config file path to load
  43. * @returns {Object} Parsed config object
  44. * @private
  45. */
  46. exports.loadConfig = filepath => {
  47. let config = {};
  48. const ext = path.extname(filepath);
  49. try {
  50. if (/\.ya?ml/.test(ext)) {
  51. config = parsers.yaml(filepath);
  52. } else if (ext === '.js') {
  53. config = parsers.js(filepath);
  54. } else {
  55. config = parsers.json(filepath);
  56. }
  57. } catch (err) {
  58. throw new Error(`failed to parse ${filepath}: ${err}`);
  59. }
  60. return config;
  61. };
  62. /**
  63. * Find ("find up") config file starting at `cwd`
  64. * @param {string} [cwd] - Current working directory
  65. * @returns {string|null} Filepath to config, if found
  66. */
  67. exports.findConfig = (cwd = process.cwd()) => {
  68. const filepath = findUp(exports.CONFIG_FILES, {cwd});
  69. if (filepath) {
  70. debug(`found config at ${filepath}`);
  71. }
  72. return filepath;
  73. };