load-plugin.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. const path_1 = __importDefault(require("path"));
  7. const chalk_1 = __importDefault(require("chalk"));
  8. const plugin_naming_1 = require("./plugin-naming");
  9. const plugin_errors_1 = require("./plugin-errors");
  10. function loadPlugin(plugins, pluginName, debug = false) {
  11. const longName = plugin_naming_1.normalizePackageName(pluginName);
  12. const shortName = plugin_naming_1.getShorthandName(longName);
  13. let plugin = null;
  14. if (pluginName.match(/\s+/u)) {
  15. throw new plugin_errors_1.WhitespacePluginError(pluginName, {
  16. pluginName: longName,
  17. });
  18. }
  19. const pluginKey = longName === pluginName ? shortName : pluginName;
  20. if (!plugins[pluginKey]) {
  21. try {
  22. plugin = require(longName);
  23. }
  24. catch (pluginLoadErr) {
  25. try {
  26. // Check whether the plugin exists
  27. require.resolve(longName);
  28. }
  29. catch (error) {
  30. // If the plugin can't be resolved, display the missing plugin error (usually a config or install error)
  31. console.error(chalk_1.default.red(`Failed to load plugin ${longName}.`));
  32. throw new plugin_errors_1.MissingPluginError(pluginName, error.message, {
  33. pluginName: longName,
  34. commitlintPath: path_1.default.resolve(__dirname, '../..'),
  35. });
  36. }
  37. // Otherwise, the plugin exists and is throwing on module load for some reason, so print the stack trace.
  38. throw pluginLoadErr;
  39. }
  40. // This step is costly, so skip if debug is disabled
  41. if (debug) {
  42. const resolvedPath = require.resolve(longName);
  43. let version = null;
  44. try {
  45. version = require(`${longName}/package.json`).version;
  46. }
  47. catch (e) {
  48. // Do nothing
  49. }
  50. const loadedPluginAndVersion = version
  51. ? `${longName}@${version}`
  52. : `${longName}, version unknown`;
  53. console.log(chalk_1.default.blue(`Loaded plugin ${pluginName} (${loadedPluginAndVersion}) (from ${resolvedPath})`));
  54. }
  55. plugins[pluginKey] = plugin;
  56. }
  57. return plugins;
  58. }
  59. exports.default = loadPlugin;
  60. //# sourceMappingURL=load-plugin.js.map