load-plugin.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 = (0, plugin_naming_1.normalizePackageName)(pluginName);
  12. const shortName = (0, 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. const message = (error === null || error === void 0 ? void 0 : error.message) || 'Unknown error occurred';
  33. throw new plugin_errors_1.MissingPluginError(pluginName, message, {
  34. pluginName: longName,
  35. commitlintPath: path_1.default.resolve(__dirname, '../..'),
  36. });
  37. }
  38. // Otherwise, the plugin exists and is throwing on module load for some reason, so print the stack trace.
  39. throw pluginLoadErr;
  40. }
  41. // This step is costly, so skip if debug is disabled
  42. if (debug) {
  43. const resolvedPath = require.resolve(longName);
  44. let version = null;
  45. try {
  46. version = require(`${longName}/package.json`).version;
  47. }
  48. catch (e) {
  49. // Do nothing
  50. }
  51. const loadedPluginAndVersion = version
  52. ? `${longName}@${version}`
  53. : `${longName}, version unknown`;
  54. console.log(chalk_1.default.blue(`Loaded plugin ${pluginName} (${loadedPluginAndVersion}) (from ${resolvedPath})`));
  55. }
  56. plugins[pluginKey] = plugin;
  57. }
  58. return plugins;
  59. }
  60. exports.default = loadPlugin;
  61. //# sourceMappingURL=load-plugin.js.map