plugin-loader.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var path = require("path");
  2. /**
  3. * Node Plugin Loader
  4. */
  5. var PluginLoader = function(less) {
  6. this.less = less;
  7. };
  8. PluginLoader.prototype.tryLoadPlugin = function(name, argument) {
  9. var plugin = this.tryRequirePlugin(name);
  10. if (plugin) {
  11. // support plugins being a function
  12. // so that the plugin can be more usable programmatically
  13. if (typeof plugin === "function") {
  14. plugin = new plugin();
  15. }
  16. if (plugin.minVersion) {
  17. if (this.compareVersion(plugin.minVersion, this.less.version) < 0) {
  18. console.log("plugin " + name + " requires version " + this.versionToString(plugin.minVersion));
  19. return null;
  20. }
  21. }
  22. if (argument) {
  23. if (!plugin.setOptions) {
  24. console.log("options have been provided but the plugin " + name + "does not support any options");
  25. return null;
  26. }
  27. try {
  28. plugin.setOptions(argument);
  29. }
  30. catch(e) {
  31. console.log("Error setting options on plugin " + name);
  32. console.log(e.message);
  33. return null;
  34. }
  35. }
  36. return plugin;
  37. }
  38. return null;
  39. };
  40. PluginLoader.prototype.compareVersion = function(aVersion, bVersion) {
  41. for (var i = 0; i < aVersion.length; i++) {
  42. if (aVersion[i] !== bVersion[i]) {
  43. return parseInt(aVersion[i]) > parseInt(bVersion[i]) ? -1 : 1;
  44. }
  45. }
  46. return 0;
  47. };
  48. PluginLoader.prototype.versionToString = function(version) {
  49. var versionString = "";
  50. for (var i = 0; i < version.length; i++) {
  51. versionString += (versionString ? "." : "") + version[i];
  52. }
  53. return versionString;
  54. };
  55. PluginLoader.prototype.tryRequirePlugin = function(name) {
  56. // is at the same level as the less.js module
  57. try {
  58. return require("../../../" + name);
  59. }
  60. catch(e) {
  61. }
  62. // is installed as a sub dependency of the current folder
  63. try {
  64. return require(path.join(process.cwd(), "node_modules", name));
  65. }
  66. catch(e) {
  67. }
  68. // is referenced relative to the current directory
  69. try {
  70. return require(path.join(process.cwd(), name));
  71. }
  72. catch(e) {
  73. }
  74. // unlikely - would have to be a dependency of where this code was running (less.js)...
  75. if (name[0] !== '.') {
  76. try {
  77. return require(name);
  78. }
  79. catch(e) {
  80. }
  81. }
  82. };
  83. PluginLoader.prototype.printUsage = function(plugins) {
  84. for (var i = 0; i < plugins.length; i++) {
  85. var plugin = plugins[i];
  86. if (plugin.printUsage) {
  87. plugin.printUsage();
  88. }
  89. }
  90. };
  91. module.exports = PluginLoader;