framework.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const path = require('path');
  3. const assert = require('assert');
  4. const fs = require('fs');
  5. const utility = require('utility');
  6. const initCwd = process.cwd();
  7. module.exports = { getFrameworkPath };
  8. /**
  9. * Find the framework directory, lookup order
  10. * - specify framework path
  11. * - get framework name from
  12. * - use egg by default
  13. * @param {Object} options - options
  14. * @param {String} options.baseDir - the current directory of application
  15. * @param {String} [options.framework] - the directory of framework
  16. * @return {String} frameworkPath
  17. */
  18. function getFrameworkPath({ framework, baseDir }) {
  19. const pkgPath = path.join(baseDir, 'package.json');
  20. assert(fs.existsSync(pkgPath), `${pkgPath} should exist`);
  21. const moduleDir = path.join(baseDir, 'node_modules');
  22. const pkg = utility.readJSONSync(pkgPath);
  23. // 1. pass framework or customEgg
  24. if (framework) {
  25. // 1.1 framework is an absolute path
  26. // framework: path.join(baseDir, 'node_modules/${frameworkName}')
  27. if (path.isAbsolute(framework)) {
  28. assert(fs.existsSync(framework), `${framework} should exist`);
  29. return framework;
  30. }
  31. // 1.2 framework is a npm package that required by application
  32. // framework: 'frameworkName'
  33. return assertAndReturn(framework, moduleDir);
  34. }
  35. // 2. framework is not specified
  36. // 2.1 use framework name from pkg.egg.framework
  37. if (pkg.egg && pkg.egg.framework) {
  38. return assertAndReturn(pkg.egg.framework, moduleDir);
  39. }
  40. // 2.2 use egg by default
  41. return assertAndReturn('egg', moduleDir);
  42. }
  43. function assertAndReturn(frameworkName, moduleDir) {
  44. const moduleDirs = new Set([
  45. moduleDir,
  46. // find framework from process.cwd, especially for test,
  47. // the application is in test/fixtures/app,
  48. // and framework is install in ${cwd}/node_modules
  49. path.join(process.cwd(), 'node_modules'),
  50. // prevent from mocking process.cwd
  51. path.join(initCwd, 'node_modules'),
  52. ]);
  53. for (const moduleDir of moduleDirs) {
  54. const frameworkPath = path.join(moduleDir, frameworkName);
  55. if (fs.existsSync(frameworkPath)) return frameworkPath;
  56. }
  57. throw new Error(`${frameworkName} is not found in ${Array.from(moduleDirs)}`);
  58. }