plugin.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict'
  2. const fs = require('graceful-fs')
  3. const path = require('path')
  4. const helper = require('./helper')
  5. const log = require('./logger').create('plugin')
  6. const IGNORED_PACKAGES = ['karma-cli', 'karma-runner.github.com']
  7. function resolve (plugins, emitter) {
  8. const modules = []
  9. function requirePlugin (name) {
  10. log.debug(`Loading plugin ${name}.`)
  11. try {
  12. modules.push(require(name))
  13. } catch (e) {
  14. if (e.code === 'MODULE_NOT_FOUND' && e.message.includes(name)) {
  15. log.error(`Cannot find plugin "${name}".\n Did you forget to install it?\n npm install ${name} --save-dev`)
  16. } else {
  17. log.error(`Error during loading "${name}" plugin:\n ${e.message}`)
  18. }
  19. emitter.emit('load_error', 'plug_in', name)
  20. }
  21. }
  22. plugins.forEach(function (plugin) {
  23. if (helper.isString(plugin)) {
  24. if (!plugin.includes('*')) {
  25. requirePlugin(plugin)
  26. return
  27. }
  28. const pluginDirectory = path.normalize(path.join(__dirname, '/../..'))
  29. const regexp = new RegExp(`^${plugin.replace('*', '.*')}`)
  30. log.debug(`Loading ${plugin} from ${pluginDirectory}`)
  31. fs.readdirSync(pluginDirectory)
  32. .filter((pluginName) => !IGNORED_PACKAGES.includes(pluginName) && regexp.test(pluginName))
  33. .forEach((pluginName) => requirePlugin(`${pluginDirectory}/${pluginName}`))
  34. } else if (helper.isObject(plugin)) {
  35. log.debug(`Loading inlined plugin (defining ${Object.keys(plugin).join(', ')}).`)
  36. modules.push(plugin)
  37. } else {
  38. log.error(`Invalid plugin ${plugin}`)
  39. emitter.emit('load_error', 'plug_in', plugin)
  40. }
  41. })
  42. return modules
  43. }
  44. exports.resolve = resolve