sort-imports.js
8.39 KB
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
/**
* @fileoverview Rule to require sorting of import declarations
* @author Christian Schuller
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "enforce sorted import declarations within modules",
category: "ECMAScript 6",
recommended: false
},
schema: [
{
type: "object",
properties: {
ignoreCase: {
type: "boolean"
},
memberSyntaxSortOrder: {
type: "array",
items: {
enum: ["none", "all", "multiple", "single"]
},
uniqueItems: true,
minItems: 4,
maxItems: 4
},
ignoreMemberSort: {
type: "boolean"
}
},
additionalProperties: false
}
],
fixable: "code"
},
create(context) {
const configuration = context.options[0] || {},
ignoreCase = configuration.ignoreCase || false,
ignoreMemberSort = configuration.ignoreMemberSort || false,
memberSyntaxSortOrder = configuration.memberSyntaxSortOrder || ["none", "all", "multiple", "single"],
sourceCode = context.getSourceCode();
let previousDeclaration = null;
/**
* Gets the used member syntax style.
*
* import "my-module.js" --> none
* import * as myModule from "my-module.js" --> all
* import {myMember} from "my-module.js" --> single
* import {foo, bar} from "my-module.js" --> multiple
*
* @param {ASTNode} node - the ImportDeclaration node.
* @returns {string} used member parameter style, ["all", "multiple", "single"]
*/
function usedMemberSyntax(node) {
if (node.specifiers.length === 0) {
return "none";
} else if (node.specifiers[0].type === "ImportNamespaceSpecifier") {
return "all";
} else if (node.specifiers.length === 1) {
return "single";
}
return "multiple";
}
/**
* Gets the group by member parameter index for given declaration.
* @param {ASTNode} node - the ImportDeclaration node.
* @returns {number} the declaration group by member index.
*/
function getMemberParameterGroupIndex(node) {
return memberSyntaxSortOrder.indexOf(usedMemberSyntax(node));
}
/**
* Gets the local name of the first imported module.
* @param {ASTNode} node - the ImportDeclaration node.
* @returns {?string} the local name of the first imported module.
*/
function getFirstLocalMemberName(node) {
if (node.specifiers[0]) {
return node.specifiers[0].local.name;
}
return null;
}
return {
ImportDeclaration(node) {
if (previousDeclaration) {
const currentMemberSyntaxGroupIndex = getMemberParameterGroupIndex(node),
previousMemberSyntaxGroupIndex = getMemberParameterGroupIndex(previousDeclaration);
let currentLocalMemberName = getFirstLocalMemberName(node),
previousLocalMemberName = getFirstLocalMemberName(previousDeclaration);
if (ignoreCase) {
previousLocalMemberName = previousLocalMemberName && previousLocalMemberName.toLowerCase();
currentLocalMemberName = currentLocalMemberName && currentLocalMemberName.toLowerCase();
}
// When the current declaration uses a different member syntax,
// then check if the ordering is correct.
// Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name.
if (currentMemberSyntaxGroupIndex !== previousMemberSyntaxGroupIndex) {
if (currentMemberSyntaxGroupIndex < previousMemberSyntaxGroupIndex) {
context.report({
node,
message: "Expected '{{syntaxA}}' syntax before '{{syntaxB}}' syntax.",
data: {
syntaxA: memberSyntaxSortOrder[currentMemberSyntaxGroupIndex],
syntaxB: memberSyntaxSortOrder[previousMemberSyntaxGroupIndex]
}
});
}
} else {
if (previousLocalMemberName &&
currentLocalMemberName &&
currentLocalMemberName < previousLocalMemberName
) {
context.report({
node,
message: "Imports should be sorted alphabetically."
});
}
}
}
if (!ignoreMemberSort) {
const importSpecifiers = node.specifiers.filter(specifier => specifier.type === "ImportSpecifier");
const getSortableName = ignoreCase ? specifier => specifier.local.name.toLowerCase() : specifier => specifier.local.name;
const firstUnsortedIndex = importSpecifiers.map(getSortableName).findIndex((name, index, array) => array[index - 1] > name);
if (firstUnsortedIndex !== -1) {
context.report({
node: importSpecifiers[firstUnsortedIndex],
message: "Member '{{memberName}}' of the import declaration should be sorted alphabetically.",
data: { memberName: importSpecifiers[firstUnsortedIndex].local.name },
fix(fixer) {
if (importSpecifiers.some(specifier => sourceCode.getComments(specifier).leading.length || sourceCode.getComments(specifier).trailing.length)) {
// If there are comments in the ImportSpecifier list, don't rearrange the specifiers.
return null;
}
return fixer.replaceTextRange(
[importSpecifiers[0].range[0], importSpecifiers[importSpecifiers.length - 1].range[1]],
importSpecifiers
// Clone the importSpecifiers array to avoid mutating it
.slice()
// Sort the array into the desired order
.sort((specifierA, specifierB) => {
const aName = getSortableName(specifierA);
const bName = getSortableName(specifierB);
return aName > bName ? 1 : -1;
})
// Build a string out of the sorted list of import specifiers and the text between the originals
.reduce((sourceText, specifier, index) => {
const textAfterSpecifier = index === importSpecifiers.length - 1
? ""
: sourceCode.getText().slice(importSpecifiers[index].range[1], importSpecifiers[index + 1].range[0]);
return sourceText + sourceCode.getText(specifier) + textAfterSpecifier;
}, "")
);
}
});
}
}
previousDeclaration = node;
}
};
}
};