]>
Commit | Line | Data |
---|---|---|
eb39fafa DC |
1 | /** |
2 | * JSCodeShift script to update meta.type in rules. | |
3 | * Run over the rules directory only. Use this command: | |
4 | * | |
5 | * jscodeshift -t tools/update-rule-types.js lib/rules/ | |
6 | * @author Nicholas C. Zakas | |
7 | */ | |
8 | "use strict"; | |
9 | ||
10 | const path = require("path"); | |
11 | const ruleTypes = require("./rule-types.json"); | |
12 | ||
13 | module.exports = (fileInfo, api) => { | |
14 | const j = api.jscodeshift; | |
15 | const source = fileInfo.source; | |
16 | const ruleName = path.basename(fileInfo.path, ".js"); | |
17 | ||
18 | // get the object literal representing the rule | |
19 | const nodes = j(source).find(j.ObjectExpression).filter(p => p.node.properties.some(node => node.key.name === "meta")); | |
20 | ||
21 | // updating logic | |
22 | return nodes.replaceWith(p => { | |
23 | ||
24 | // gather important nodes from the rule | |
25 | const metaNode = p.node.properties.find(node => node.key.name === "meta"); | |
26 | ||
27 | // if there's no properties, just exit | |
28 | if (!metaNode.value.properties) { | |
29 | return p.node; | |
30 | } | |
31 | ||
32 | const typeNode = metaNode.value.properties.find(node => node.key.name === "type"); | |
eb39fafa DC |
33 | |
34 | let ruleType; | |
35 | ||
eb39fafa DC |
36 | if (ruleName in ruleTypes) { |
37 | ruleType = ruleTypes[ruleName]; | |
eb39fafa DC |
38 | } |
39 | ||
40 | if (typeNode) { | |
41 | ||
42 | // update existing type node | |
43 | typeNode.value = j.literal(ruleType); | |
44 | } else { | |
45 | ||
46 | // add new type node if one doesn't exist | |
47 | const newProp = j.property( | |
48 | "init", | |
49 | j.identifier("type"), | |
50 | j.literal(ruleType) | |
51 | ); | |
52 | ||
53 | p.node.properties[0].value.properties.unshift(newProp); | |
54 | } | |
55 | ||
56 | return p.node; | |
57 | }).toSource(); | |
58 | }; |