plugin-utils.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. * borrowing from: https://github.com/hexojs/hexo/blob/d1db459c92a4765620343b95789361cbbc6414c5/lib/hexo/load_plugins.js#L17
  63. *
  64. * @returns
  65. *
  66. * @memberOf PluginService
  67. */
  68. listPluginNames(rootDir) {
  69. var packagePath = path.join(rootDir, 'package.json');
  70. // Make sure package.json exists
  71. if (!fs.existsSync(packagePath)) {
  72. return [];
  73. }
  74. // Read package.json and find dependencies
  75. const content = fs.readFileSync(packagePath);
  76. const json = JSON.parse(content);
  77. const deps = json.dependencies || {};
  78. return Object.keys(deps).filter((name) => {
  79. // Ignore plugins whose name is not started with "crowi-"
  80. return /^crowi-plugin-/.test(name);
  81. });
  82. }
  83. }
  84. module.exports = PluginUtils