1 | 'use strict'
|
2 | exports.__esModule = true
|
3 |
|
4 | const moduleRequire = require('./module-require').default
|
5 | const extname = require('path').extname
|
6 |
|
7 | const log = require('debug')('eslint-plugin-import:parse')
|
8 |
|
9 | exports.default = function parse(path, content, context) {
|
10 |
|
11 | if (context == null) throw new Error('need context to parse properly')
|
12 |
|
13 | let parserOptions = context.parserOptions
|
14 | const parserPath = getParserPath(path, context)
|
15 |
|
16 | if (!parserPath) throw new Error('parserPath is required!')
|
17 |
|
18 |
|
19 | parserOptions = Object.assign({}, parserOptions)
|
20 | parserOptions.ecmaFeatures = Object.assign({}, parserOptions.ecmaFeatures)
|
21 |
|
22 |
|
23 | parserOptions.comment = true
|
24 | parserOptions.attachComment = true
|
25 | parserOptions.tokens = true
|
26 |
|
27 |
|
28 | parserOptions.loc = true
|
29 | parserOptions.range = true
|
30 |
|
31 |
|
32 |
|
33 | parserOptions.filePath = path
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | delete parserOptions.project
|
40 | delete parserOptions.projects
|
41 |
|
42 |
|
43 | const parser = moduleRequire(parserPath)
|
44 |
|
45 | if (typeof parser.parseForESLint === 'function') {
|
46 | let ast
|
47 | try {
|
48 | ast = parser.parseForESLint(content, parserOptions).ast
|
49 | } catch (e) {
|
50 |
|
51 | }
|
52 | if (!ast || typeof ast !== 'object') {
|
53 | console.warn(
|
54 | '`parseForESLint` from parser `' +
|
55 | parserPath +
|
56 | '` is invalid and will just be ignored'
|
57 | )
|
58 | } else {
|
59 | return ast
|
60 | }
|
61 | }
|
62 |
|
63 | return parser.parse(content, parserOptions)
|
64 | }
|
65 |
|
66 | function getParserPath(path, context) {
|
67 | const parsers = context.settings['import/parsers']
|
68 | if (parsers != null) {
|
69 | const extension = extname(path)
|
70 | for (let parserPath in parsers) {
|
71 | if (parsers[parserPath].indexOf(extension) > -1) {
|
72 |
|
73 | log('using alt parser:', parserPath)
|
74 | return parserPath
|
75 | }
|
76 | }
|
77 | }
|
78 |
|
79 | return context.parserPath
|
80 | }
|