plugin-utils.js 1.8 KB

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