-
Notifications
You must be signed in to change notification settings - Fork 4
/
transform-fix-async-overly.ts
101 lines (89 loc) · 2.62 KB
/
transform-fix-async-overly.ts
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
/**
* 1. Find async functions
* 2. Check if there is any await expression inside the function
* 3. If there wasn't any await expression, then remove async from function expression.
*/
import { FileInfo, API, Options, ASTPath } from "jscodeshift";
import {
findParentFunction,
getFunctionLocation,
setFunctionNotAsync,
} from "./utils";
const debug = require("debug")("transform:fix-async-overly");
const debug2 = require("debug")("transform:print:fix-async-overly");
module.exports = function (fileInfo: FileInfo, { j }: API, options: Options) {
debug(
`**************************************************
*** ${fileInfo.path}
**************************************************`
);
let fileChanged = false;
const rootCollection = j(fileInfo.source);
// debug(rootCollection)
const checkIfAsyncNeeded = (p: ASTPath) => {
debug("check", j(p).toSource());
// get the function location
const { start, end } = getFunctionLocation(p) || {};
debug({ start, end });
// find await expression
const subCollection = j(p);
let foundAwait = false;
subCollection.find(j.AwaitExpression).map((p2) => {
// find the parent function
const myParentFunction = findParentFunction(p2);
if (myParentFunction) {
// check if p2 is p
const { start: start2, end: end2 } =
getFunctionLocation(myParentFunction) || {};
debug({ start2, end2 });
if (start2?.line === start?.line && start2?.column === start?.column) {
foundAwait = true;
}
}
return null;
});
debug("found await:", foundAwait);
if (!foundAwait) {
// remove async from function expression
if (setFunctionNotAsync(p)) {
fileChanged = true;
}
}
};
// find all async expression
rootCollection.find(j.ArrowFunctionExpression).map((p) => {
if (p.value.async) {
checkIfAsyncNeeded(p);
}
return null;
});
rootCollection.find(j.FunctionDeclaration).map((p) => {
if (p.value.async) {
checkIfAsyncNeeded(p);
}
return null;
});
rootCollection.find(j.FunctionExpression).map((p) => {
if (p.value.async) {
checkIfAsyncNeeded(p);
}
return null;
});
rootCollection.find(j.ObjectMethod).map((p) => {
if (p.value.async) {
checkIfAsyncNeeded(p);
}
return null;
});
rootCollection.find(j.ClassMethod).map((p) => {
if (p.value.async) {
checkIfAsyncNeeded(p);
}
return null;
});
debug("**************************************************");
if (fileChanged) {
debug2("file changed:", fileInfo.path);
return rootCollection.toSource();
}
};