-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
68 lines (54 loc) · 1.78 KB
/
utils.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
let j;
export function init(api) {
j = api.jscodeshift;
const COMPUTABLES = [
{ type: j.ClassProperty, fieldName: 'key' },
{ type: j.MemberExpression, fieldName: 'property' },
{ type: j.MethodDefinition, fieldName: 'key' },
{ type: j.Property, fieldName: 'key' },
{ type: j.PropertyPattern, fieldName: 'key' },
];
j.registerMethods({
findIdentifier(name) {
return this.find(j.Identifier, {name});
},
findVariableReference(name) {
function isNodeFieldSupportType(node, fieldName, type) {
function getNodeTypeDef() {
const typeDef = j.types.Type.def(node.type);
if (!typeDef.finalized) {
throw new Error(`Type '${node.type}' is not finalized.`);
}
return typeDef;
}
function getNodeFieldType() {
return getNodeTypeDef().allFields[fieldName].type;
}
return getNodeFieldType().check({ type });
}
function isVariableReference(path) {
const parent = path.parent.node;
const fieldName = path.name;
if (!isNodeFieldSupportType(parent, fieldName, 'Expression')) {
return false;
}
for (const computable of COMPUTABLES) {
if (computable.type.check(parent)) {
return fieldName !== computable.fieldName || parent.computed;
}
}
return true;
}
return this.findIdentifier(name).filter(isVariableReference);
},
});
}
export function equalTo(right) {
return left => j.types.astNodesAreEquivalent(left, right);
}
export function getRequireCall(path, moduleName) {
const call = path
.findVariableDeclarators()
.filter(j.filters.VariableDeclarator.requiresModule(moduleName));
return call.size() == 1 ? call.get() : null;
}