plugin-utils.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const path = require('path');
  2. const fs = require('graceful-fs');
  3. const PluginUtilsV2 = require('./plugin-utils-v2');
  4. const pluginUtilsV2 = new PluginUtilsV2();
  5. class PluginUtils {
  6. /**
  7. * return a definition objects that has following structure:
  8. *
  9. * {
  10. * name: 'growi-plugin-X',
  11. * meta: require('growi-plugin-X'),
  12. * entries: [
  13. * 'growi-plugin-X/lib/client-entry'
  14. * ]
  15. * }
  16. *
  17. * @param {string} pluginName
  18. * @return
  19. * @memberOf PluginService
  20. */
  21. generatePluginDefinition(name, isForClient = false) {
  22. const meta = require(name);
  23. let definition;
  24. switch (meta.pluginSchemaVersion) {
  25. // v1 is deprecated
  26. case 1:
  27. console.log('pluginSchemaVersion 1 is deprecated');
  28. debug('pluginSchemaVersion 1 is deprecated');
  29. break;
  30. // v2 or above
  31. case 2:
  32. default:
  33. definition = pluginUtilsV2.generatePluginDefinition(name, isForClient);
  34. }
  35. return definition;
  36. }
  37. /**
  38. * list plugin module objects
  39. * that starts with 'growi-plugin-' or 'crowi-plugin-'
  40. * borrowing from: https://github.com/hexojs/hexo/blob/d1db459c92a4765620343b95789361cbbc6414c5/lib/hexo/load_plugins.js#L17
  41. *
  42. * @returns array of objects
  43. * [
  44. * { name: 'growi-plugin-...', version: '1.0.0' },
  45. * { name: 'growi-plugin-...', version: '1.0.0' },
  46. * ...
  47. * ]
  48. *
  49. * @memberOf PluginService
  50. */
  51. listPlugins(rootDir) {
  52. var packagePath = path.join(rootDir, 'package.json');
  53. // Make sure package.json exists
  54. if (!fs.existsSync(packagePath)) {
  55. return [];
  56. }
  57. // Read package.json and find dependencies
  58. const content = fs.readFileSync(packagePath);
  59. const json = JSON.parse(content);
  60. const deps = json.dependencies || {};
  61. let objs = {};
  62. Object.keys(deps).forEach((name) => {
  63. if (/^(crowi|growi)-plugin-/.test(name)) {
  64. objs[name] = deps[name];
  65. }
  66. });
  67. return objs;
  68. }
  69. /**
  70. * list plugin module names that starts with 'crowi-plugin-'
  71. *
  72. * @returns array of plugin names
  73. *
  74. * @memberOf PluginService
  75. */
  76. listPluginNames(rootDir) {
  77. const plugins = this.listPlugins(rootDir);
  78. return Object.keys(plugins);
  79. }
  80. }
  81. module.exports = PluginUtils;