-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathmeta-property-ordering.js
78 lines (67 loc) · 2.11 KB
/
meta-property-ordering.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
/**
* @fileoverview Enforces the order of meta properties
*/
'use strict';
const { getKeyName, getRuleInfo } = require('../utils');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: 'Enforces the order of meta properties',
category: 'Rules',
recommended: false,
},
type: 'suggestion',
fixable: 'code',
schema: [{
type: 'array',
elements: { type: 'string' },
}],
},
create (context) {
const sourceCode = context.getSourceCode();
const info = getRuleInfo(sourceCode.ast);
const message = 'The meta properties should be placed in a consistent order: [{{order}}].';
const order = context.options[0] || ['type', 'docs', 'fixable', 'schema', 'messages'];
const orderMap = new Map(order.map((name, i) => [name, i]));
return {
Program () {
if (
!info ||
!info.meta ||
info.meta.properties.length < 2
) {
return;
}
const propsActual = info.meta.properties
.filter(prop => orderMap.has(getKeyName(prop)));
for (let i = 1, j = propsActual.length; i < j; i += 1) {
const last = propsActual[i - 1];
const curr = propsActual[i];
if (order.indexOf(getKeyName(last)) > order.indexOf(getKeyName(curr))) {
const propsExpected = propsActual
.slice()
.sort((a, b) => orderMap.get(getKeyName(a)) - orderMap.get(getKeyName(b)));
context.report({
node: curr,
message,
data: {
order: propsExpected.map(getKeyName).join(', '),
},
fix (fixer) {
return propsActual.map((prop, k) => {
return fixer.replaceText(
prop,
sourceCode.getText(propsExpected[k])
);
});
},
});
}
}
},
};
},
};