2
0

plugin-utils.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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: 'crowi-plugin-X',
  11. * meta: require('crowi-plugin-X'),
  12. * entries: [
  13. * 'crowi-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 that starts with 'crowi-plugin-'
  39. * borrowing from: https://github.com/hexojs/hexo/blob/d1db459c92a4765620343b95789361cbbc6414c5/lib/hexo/load_plugins.js#L17
  40. *
  41. * @returns array of objects
  42. * [
  43. * { name: 'crowi-plugin-...', version: '1.0.0' },
  44. * { name: 'crowi-plugin-...', version: '1.0.0' },
  45. * ...
  46. * ]
  47. *
  48. * @memberOf PluginService
  49. */
  50. listPlugins(rootDir) {
  51. var packagePath = path.join(rootDir, 'package.json');
  52. // Make sure package.json exists
  53. if (!fs.existsSync(packagePath)) {
  54. return [];
  55. }
  56. // Read package.json and find dependencies
  57. const content = fs.readFileSync(packagePath);
  58. const json = JSON.parse(content);
  59. const deps = json.dependencies || {};
  60. let objs = {};
  61. Object.keys(deps).forEach((name) => {
  62. if (/^crowi-plugin-/.test(name)) {
  63. objs[name] = deps[name];
  64. }
  65. });
  66. return objs;
  67. }
  68. /**
  69. * list plugin module names that starts with 'crowi-plugin-'
  70. *
  71. * @returns array of plugin names
  72. *
  73. * @memberOf PluginService
  74. */
  75. listPluginNames(rootDir) {
  76. const plugins = this.listPlugins(rootDir);
  77. return Object.keys(plugins);
  78. }
  79. }
  80. module.exports = PluginUtils