plugin-utils.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const path = require('path');
  2. const fs = require('hexo-fs');
  3. class PluginUtils {
  4. /**
  5. * return a array of definition objects that has following structure:
  6. *
  7. * [
  8. * {
  9. * name: 'crowi-plugin-X',
  10. * meta: require('crowi-plugin-X'),
  11. * entries: [
  12. * require('crowi-plugin-X/lib/client-entry')
  13. * ]
  14. * },
  15. * ]
  16. *
  17. * @param {string} rootDir Crowi Project root dir
  18. * @return
  19. * @memberOf PluginService
  20. */
  21. generatePluginDefinitions(rootDir, isForClient = false) {
  22. return this.listPluginNames(rootDir)
  23. .map((name) => {
  24. const meta = require(name);
  25. const entries = (isForClient) ? meta.clientEntries : meta.serverEntries;
  26. return {
  27. name: name,
  28. meta: meta,
  29. entries: entries.map((entryPath) => {
  30. return require(entryPath);
  31. })
  32. }
  33. });
  34. }
  35. /**
  36. * list plugin module names that starts with 'crowi-plugin-'
  37. * borrowing from: https://github.com/hexojs/hexo/blob/d1db459c92a4765620343b95789361cbbc6414c5/lib/hexo/load_plugins.js#L17
  38. *
  39. * @returns
  40. *
  41. * @memberOf PluginService
  42. */
  43. listPluginNames(rootDir) {
  44. var packagePath = path.join(rootDir, 'package.json');
  45. // Make sure package.json exists
  46. return fs.exists(packagePath).then(function(exist) {
  47. if (!exist) return [];
  48. // Read package.json and find dependencies
  49. return fs.readFile(packagePath).then(function(content) {
  50. var json = JSON.parse(content);
  51. var deps = json.dependencies || {};
  52. return Object.keys(deps);
  53. });
  54. }).filter(function(name) {
  55. // Ignore plugins whose name is not started with "crowi-"
  56. return /^crowi-plugin-/.test(name);
  57. });
  58. }
  59. }
  60. module.exports = PluginUtils