/
sortKeys.js
254 lines (218 loc) · 6.83 KB
/
sortKeys.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
import _ from 'lodash';
import {
getParameterName,
} from '../utilities';
const defaults = {
caseSensitive: true,
natural: false,
};
const schema = [
{
enum: ['asc', 'desc'],
type: 'string',
},
{
additionalProperties: false,
properties: {
caseSensitive: {
type: 'boolean',
},
natural: {
type: 'boolean',
},
},
type: 'object',
},
];
/**
* Functions to compare the order of two strings
*
* Based on a similar function from eslint's sort-keys rule.
* https://github.com/eslint/eslint/blob/master/lib/rules/sort-keys.js
*
* @private
*/
const isValidOrders = {
asc (str1, str2) {
return str1 <= str2;
},
ascI (str1, str2) {
return str1.toLowerCase() <= str2.toLowerCase();
},
ascIN (str1, str2) {
return isValidOrders.naturalCompare(str1.toLowerCase(), str2.toLowerCase()) <= 0;
},
ascN (str1, str2) {
return isValidOrders.naturalCompare(str1, str2) <= 0;
},
desc (str1, str2) {
return isValidOrders.asc(str2, str1);
},
descI (str1, str2) {
return isValidOrders.ascI(str2, str1);
},
descIN (str1, str2) {
return isValidOrders.ascIN(str2, str1);
},
descN (str1, str2) {
return isValidOrders.ascN(str2, str1);
},
naturalCompare (str1, str2) {
return str1.localeCompare(str2, 'en-US', {numeric: true});
},
};
const generateOrderedList = (context, sort, properties) => {
const source = context.getSourceCode();
const items = properties.map((property) => {
const name = getParameterName(property, context);
const commentsBefore = source.getCommentsBefore(property);
const startIndex = commentsBefore.length > 0 ?
commentsBefore[0].range[0] :
property.range[0];
if (property.type === 'ObjectTypeSpreadProperty' || !property.value) {
// NOTE: It could but currently does not fix recursive generic type arguments in GenericTypeAnnotation within ObjectTypeSpreadProperty.
// Maintain everything between the start of property including leading comments and the nextPunctuator `,` or `}`:
const nextPunctuator = source.getTokenAfter(property, {
filter: (token) => {
return token.type === 'Punctuator';
},
});
const beforePunctuator = source.getTokenBefore(nextPunctuator, {
includeComments: true,
});
const text = source.getText().slice(startIndex, beforePunctuator.range[1]);
return [property, text];
}
const colonToken = source.getTokenBefore(property.value, {
filter: (token) => {
return token.value === ':';
},
});
// Preserve all code until the colon verbatim:
const key = source.getText().slice(startIndex, colonToken.range[0]);
let value;
if (property.value.type === 'ObjectTypeAnnotation') {
// eslint-disable-next-line no-use-before-define
value = ' ' + generateFix(property.value, context, sort);
} else {
// NOTE: It could but currently does not fix recursive generic type arguments in GenericTypeAnnotation.
// Maintain everything between the `:` and the next Punctuator `,` or `}`:
const nextPunctuator = source.getTokenAfter(property, {
filter: (token) => {
return token.type === 'Punctuator';
},
});
const beforePunctuator = source.getTokenBefore(nextPunctuator, {
includeComments: true,
});
const text = source.getText().slice(colonToken.range[1], beforePunctuator.range[1]);
value = text;
}
return [property, name, key, value];
});
const itemGroups = [[]];
let itemGroupIndex = 0;
items.forEach((item) => {
if (item[0].type === 'ObjectTypeSpreadProperty') {
++itemGroupIndex;
itemGroups[itemGroupIndex] = [item];
++itemGroupIndex;
itemGroups[itemGroupIndex] = [];
} else {
itemGroups[itemGroupIndex].push(item);
}
});
const orderedList = [];
itemGroups.forEach((itemGroup) => {
if (itemGroup[0] && itemGroup[0].type !== 'ObjectTypeSpreadProperty') {
itemGroup
.sort((first, second) => {
return sort(first[1], second[1]) ? -1 : 1;
});
}
orderedList.push(...itemGroup.map((item) => {
if (item.length === 2) {
return item[1];
}
return item[2] + ':' + item[3];
}));
});
return orderedList;
};
const generateFix = (node, context, sort) => {
// this could be done much more cleanly in ESLint >=4
// as we can apply multiple fixes. That also means we can
// maintain code style in a much nicer way
let nodeText;
const newTypes = generateOrderedList(context, sort, node.properties);
const source = context.getSourceCode(node);
const originalSubstring = source.getText(node);
nodeText = originalSubstring;
node.properties.forEach((property, index) => {
const nextPunctuator = source.getTokenAfter(property, {
filter: (token) => {
return token.type === 'Punctuator';
},
});
const beforePunctuator = source.getTokenBefore(nextPunctuator, {
includeComments: true,
});
const commentsBefore = source.getCommentsBefore(property);
const startIndex = commentsBefore.length > 0 ?
commentsBefore[0].range[0] :
property.range[0];
const subString = source.getText().slice(
startIndex,
beforePunctuator.range[1]
);
nodeText = nodeText.replace(subString, '$' + index);
});
newTypes.forEach((item, index) => {
nodeText = nodeText.replace('$' + index, item);
});
return nodeText;
};
const create = (context) => {
const order = _.get(context, ['options', 0], 'asc');
const {natural, caseSensitive} = _.get(context, ['options', 1], defaults);
const insensitive = caseSensitive === false;
let prev;
const checkKeyOrder = (node) => {
prev = null;
_.forEach(node.properties, (identifierNode) => {
const current = getParameterName(identifierNode, context);
const last = prev;
// keep track of the last token
prev = current || last;
if (!last || !current) {
return;
}
const isValidOrder = isValidOrders[order + (insensitive ? 'I' : '') + (natural ? 'N' : '')];
if (isValidOrder(last, current) === false) {
context.report({
data: {
current,
insensitive: insensitive ? 'insensitive ' : '',
last,
natural: natural ? 'natural ' : '',
order,
},
fix (fixer) {
const nodeText = generateFix(node, context, isValidOrder);
return fixer.replaceText(node, nodeText);
},
loc: identifierNode.loc,
message: 'Expected type annotations to be in {{natural}}{{insensitive}}{{order}}ending order. "{{current}}" should be before "{{last}}".',
node: identifierNode,
});
}
});
};
return {
ObjectTypeAnnotation: checkKeyOrder,
};
};
export default {
create,
schema,
};