index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. 'use strict'
  2. const nodePath = require('path')
  3. module.exports = presetLoader(require)
  4. module.exports.presetLoader = presetLoader
  5. function presetLoader (requireMethod) {
  6. return path => {
  7. let name = ''
  8. let scope = ''
  9. let absolutePath = ''
  10. if (typeof path === 'string') {
  11. name = path.toLowerCase()
  12. if (nodePath.isAbsolute(path)) {
  13. absolutePath = path
  14. }
  15. } else if (typeof path === 'object' && path.name) {
  16. // Rather than a string preset name, options.preset can be an object
  17. // with a "name" key indicating the preset to load; additinoal key/value
  18. // pairs are assumed to be configuration for the preset. See the documentation
  19. // for a given preset for configuration available.
  20. name = path.name.toLowerCase()
  21. if (nodePath.isAbsolute(path.name)) {
  22. absolutePath = path.name
  23. }
  24. } else {
  25. throw Error('preset must be string or object with key name')
  26. }
  27. if (!absolutePath) {
  28. if (name[0] === '@') {
  29. const parts = name.split('/')
  30. scope = parts.shift() + '/'
  31. name = parts.join('/')
  32. }
  33. if (!name.startsWith('conventional-changelog-')) {
  34. name = `conventional-changelog-${name}`
  35. }
  36. }
  37. try {
  38. const config = requireMethod(absolutePath || `${scope}${name}`)
  39. // rather than returning a promise, presets can return a builder function
  40. // which accepts a config object (allowing for customization) and returns
  41. // a promise.
  42. if (config && !config.then && typeof path === 'object') {
  43. return config(path)
  44. } else {
  45. // require returned a promise that resolves to a config object.
  46. return config
  47. }
  48. } catch (_) {
  49. throw Error('does not exist')
  50. }
  51. }
  52. }