readConfigFileAndSetRootDir.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. function _path() {
  7. const data = _interopRequireDefault(require('path'));
  8. _path = function _path() {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _fs() {
  14. const data = _interopRequireDefault(require('fs'));
  15. _fs = function _fs() {
  16. return data;
  17. };
  18. return data;
  19. }
  20. var _jsonlint = _interopRequireDefault(require('./vendor/jsonlint'));
  21. var _constants = require('./constants');
  22. function _interopRequireDefault(obj) {
  23. return obj && obj.__esModule ? obj : {default: obj};
  24. }
  25. /**
  26. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  27. *
  28. * This source code is licensed under the MIT license found in the
  29. * LICENSE file in the root directory of this source tree.
  30. */
  31. // @ts-ignore: vendored
  32. // Read the configuration and set its `rootDir`
  33. // 1. If it's a `package.json` file, we look into its "jest" property
  34. // 2. For any other file, we just require it.
  35. var _default = configPath => {
  36. const isJSON = configPath.endsWith('.json');
  37. let configObject;
  38. try {
  39. configObject = require(configPath);
  40. } catch (error) {
  41. if (isJSON) {
  42. throw new Error(
  43. `Jest: Failed to parse config file ${configPath}\n` +
  44. ` ${_jsonlint.default.errors(
  45. _fs().default.readFileSync(configPath, 'utf8')
  46. )}`
  47. );
  48. } else {
  49. throw error;
  50. }
  51. }
  52. if (configPath.endsWith(_constants.PACKAGE_JSON)) {
  53. // Event if there's no "jest" property in package.json we will still use
  54. // an empty object.
  55. configObject = configObject.jest || {};
  56. }
  57. if (configObject.rootDir) {
  58. // We don't touch it if it has an absolute path specified
  59. if (!_path().default.isAbsolute(configObject.rootDir)) {
  60. // otherwise, we'll resolve it relative to the file's __dirname
  61. configObject.rootDir = _path().default.resolve(
  62. _path().default.dirname(configPath),
  63. configObject.rootDir
  64. );
  65. }
  66. } else {
  67. // If rootDir is not there, we'll set it to this file's __dirname
  68. configObject.rootDir = _path().default.dirname(configPath);
  69. }
  70. return configObject;
  71. };
  72. exports.default = _default;