forked from import-js/eslint-plugin-import
-
Notifications
You must be signed in to change notification settings - Fork 2
/
order.js
277 lines (247 loc) · 8.49 KB
/
order.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
'use strict'
import importType from '../core/importType'
import isStaticRequire from '../core/staticRequire'
const defaultGroups = ['builtin', 'external', 'parent', 'sibling', 'index']
// REPORTING
function reverse(array) {
return array.map(function (v) {
return {
name: v.name,
rank: -v.rank,
node: v.node,
}
}).reverse()
}
function findOutOfOrder(imported) {
if (imported.length === 0) {
return []
}
let maxSeenRankNode = imported[0]
return imported.filter(function (importedModule) {
const res = importedModule.rank < maxSeenRankNode.rank
if (maxSeenRankNode.rank < importedModule.rank) {
maxSeenRankNode = importedModule
}
return res
})
}
function findOutOfAlphabeticalOrder(imported, sortOrder = 'ignore') {
if (imported.length === 0 || sortOrder === 'ignore') {
return []
}
let maxSeenRankNode = imported[0]
let maxSeenAlphabeticalNode = imported[0]
return imported.filter(function (importedModule) {
if (maxSeenRankNode.rank < importedModule.rank) {
maxSeenRankNode = importedModule
// New group, reset max alphabetical node
maxSeenAlphabeticalNode = importedModule
}
const resAlphabetical = (importedModule.name < maxSeenAlphabeticalNode.name)
if (maxSeenAlphabeticalNode.name < importedModule.name) {
maxSeenAlphabeticalNode = importedModule
}
return resAlphabetical
})
}
function reportOutOfOrder(context, imported, outOfOrder, order) {
outOfOrder.forEach(function (imp) {
const found = imported.find(function hasHigherRank(importedItem) {
return importedItem.rank > imp.rank
})
context.report(imp.node, '`' + imp.name + '` import should occur ' + order +
' import of `' + found.name + '`')
})
}
function reportOutOfAlphabeticalOrder(context, imported, outOfOrder, order) {
outOfOrder.forEach(function (imp) {
const found = imported.find(function hasHigherAlphabeticalOrder(importedItem) {
return importedItem.name > imp.name && importedItem.rank === imp.rank
})
context.report(imp.node, '`' + imp.name + '` import should occur ' + order +
' import of `' + found.name + '`')
})
}
function makeOutOfOrderReport(context, imported) {
const outOfOrder = findOutOfOrder(imported)
if (!outOfOrder.length) {
return
}
// There are things to report. Try to minimize the number of reported errors.
const reversedImported = reverse(imported)
const reversedOrder = findOutOfOrder(reversedImported)
if (reversedOrder.length < outOfOrder.length) {
reportOutOfOrder(context, reversedImported, reversedOrder, 'after')
return
}
reportOutOfOrder(context, imported, outOfOrder, 'before')
}
function makeOutOfAlphabeticalOrderReport(context, imported, sortOrder) {
const outOfOrder = findOutOfAlphabeticalOrder(imported, sortOrder)
if (!outOfOrder.length) {
return
}
// There are things to report. Try to minimize the number of reported errors.
const reversedImported = reverse(imported)
const reversedOrder = findOutOfAlphabeticalOrder(reversedImported, sortOrder)
if (reversedOrder.length < outOfOrder.length && reversedOrder.length > 0) {
reportOutOfAlphabeticalOrder(context, reversedImported, reversedOrder, 'after')
return
}
reportOutOfAlphabeticalOrder(context, imported, outOfOrder, 'before')
}
// DETECTING
function computeRank(context, ranks, name, type) {
return ranks[importType(name, context)] +
(type === 'import' ? 0 : 100)
}
function registerNode(context, node, name, type, ranks, imported) {
const rank = computeRank(context, ranks, name, type)
if (rank !== -1) {
imported.push({name, rank, node})
}
}
function isInVariableDeclarator(node) {
return node &&
(node.type === 'VariableDeclarator' || isInVariableDeclarator(node.parent))
}
const types = ['builtin', 'external', 'internal', 'parent', 'sibling', 'index']
// Creates an object with type-rank pairs.
// Example: { index: 0, sibling: 1, parent: 1, external: 1, builtin: 2, internal: 2 }
// Will throw an error if it contains a type that does not exist, or has a duplicate
function convertGroupsToRanks(groups) {
const rankObject = groups.reduce(function(res, group, index) {
if (typeof group === 'string') {
group = [group]
}
group.forEach(function(groupItem) {
if (types.indexOf(groupItem) === -1) {
throw new Error('Incorrect configuration of the rule: Unknown type `' +
JSON.stringify(groupItem) + '`')
}
if (res[groupItem] !== undefined) {
throw new Error('Incorrect configuration of the rule: `' + groupItem + '` is duplicated')
}
res[groupItem] = index
})
return res
}, {})
const omittedTypes = types.filter(function(type) {
return rankObject[type] === undefined
})
return omittedTypes.reduce(function(res, type) {
res[type] = groups.length
return res
}, rankObject)
}
function makeNewlinesBetweenReport (context, imported, newlinesBetweenImports) {
const getNumberOfEmptyLinesBetween = (currentImport, previousImport) => {
const linesBetweenImports = context.getSourceCode().lines.slice(
previousImport.node.loc.end.line,
currentImport.node.loc.start.line - 1
)
return linesBetweenImports.filter((line) => !line.trim().length).length
}
let previousImport = imported[0]
imported.slice(1).forEach(function(currentImport) {
if (newlinesBetweenImports === 'always') {
if (currentImport.rank !== previousImport.rank
&& getNumberOfEmptyLinesBetween(currentImport, previousImport) === 0)
{
context.report(
previousImport.node, 'There should be at least one empty line between import groups'
)
} else if (currentImport.rank === previousImport.rank
&& getNumberOfEmptyLinesBetween(currentImport, previousImport) > 0)
{
context.report(
previousImport.node, 'There should be no empty line within import group'
)
}
} else {
if (getNumberOfEmptyLinesBetween(currentImport, previousImport) > 0) {
context.report(previousImport.node, 'There should be no empty line between import groups')
}
}
previousImport = currentImport
})
}
module.exports = {
meta: {
docs: {},
schema: [
{
type: 'object',
properties: {
groups: {
type: 'array',
},
'newlines-between': {
enum: [ 'ignore', 'always', 'never' ],
},
'sort-order': {
enum: [ 'alphabetical', 'ignore' ],
},
},
additionalProperties: false,
},
],
},
create: function importOrderRule (context) {
const options = context.options[0] || {}
const newlinesBetweenImports = options['newlines-between'] || 'ignore'
const sortOrder = options['sort-order'] || 'ignore'
let ranks
try {
ranks = convertGroupsToRanks(options.groups || defaultGroups)
} catch (error) {
// Malformed configuration
return {
Program: function(node) {
context.report(node, error.message)
},
}
}
let imported = []
let level = 0
function incrementLevel() {
level++
}
function decrementLevel() {
level--
}
return {
ImportDeclaration: function handleImports(node) {
if (node.specifiers.length) { // Ignoring unassigned imports
const name = node.source.value
registerNode(context, node, name, 'import', ranks, imported)
}
},
CallExpression: function handleRequires(node) {
if (level !== 0 || !isStaticRequire(node) || !isInVariableDeclarator(node.parent)) {
return
}
const name = node.arguments[0].value
registerNode(context, node, name, 'require', ranks, imported)
},
'Program:exit': function reportAndReset() {
makeOutOfOrderReport(context, imported)
makeOutOfAlphabeticalOrderReport(context, imported, sortOrder)
if (newlinesBetweenImports !== 'ignore') {
makeNewlinesBetweenReport(context, imported, newlinesBetweenImports)
}
imported = []
},
FunctionDeclaration: incrementLevel,
FunctionExpression: incrementLevel,
ArrowFunctionExpression: incrementLevel,
BlockStatement: incrementLevel,
ObjectExpression: incrementLevel,
'FunctionDeclaration:exit': decrementLevel,
'FunctionExpression:exit': decrementLevel,
'ArrowFunctionExpression:exit': decrementLevel,
'BlockStatement:exit': decrementLevel,
'ObjectExpression:exit': decrementLevel,
}
},
}