parse.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict"
  2. exports.__esModule = true
  3. const moduleRequire = require('./module-require').default
  4. const extname = require('path').extname
  5. const log = require('debug')('eslint-plugin-import:parse')
  6. exports.default = function parse(path, content, context) {
  7. if (context == null) throw new Error('need context to parse properly')
  8. let parserOptions = context.parserOptions
  9. const parserPath = getParserPath(path, context)
  10. if (!parserPath) throw new Error('parserPath is required!')
  11. // hack: espree blows up with frozen options
  12. parserOptions = Object.assign({}, parserOptions)
  13. parserOptions.ecmaFeatures = Object.assign({}, parserOptions.ecmaFeatures)
  14. // always include and attach comments
  15. parserOptions.comment = true
  16. parserOptions.attachComment = true
  17. // attach node locations
  18. parserOptions.loc = true
  19. // provide the `filePath` like eslint itself does, in `parserOptions`
  20. // https://github.com/eslint/eslint/blob/3ec436ee/lib/linter.js#L637
  21. parserOptions.filePath = path
  22. // require the parser relative to the main module (i.e., ESLint)
  23. const parser = moduleRequire(parserPath)
  24. return parser.parse(content, parserOptions)
  25. }
  26. function getParserPath(path, context) {
  27. const parsers = context.settings['import/parsers']
  28. if (parsers != null) {
  29. const extension = extname(path)
  30. for (let parserPath in parsers) {
  31. if (parsers[parserPath].indexOf(extension) > -1) {
  32. // use this alternate parser
  33. log('using alt parser:', parserPath)
  34. return parserPath
  35. }
  36. }
  37. }
  38. // default to use ESLint parser
  39. return context.parserPath
  40. }