-
Notifications
You must be signed in to change notification settings - Fork 20
/
extract.ts
172 lines (141 loc) · 5.06 KB
/
extract.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
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
import * as ts from "typescript";
const fs = require('fs');
const { green, red } = require('kleur');
const functionsToIgnore: string[] = []; // optionally ['require', 'parseInt', 'exec', 'reject', 'resolve'];
const allFunctions: string[] = [];
const calledFunctions: Map<string, string[]> = new Map();
let currentFunction = undefined; // to keep track of which function we are inside
// =================================================================================================
/**
* Recursively walk through TypeScript code extracting
* - function declarations and
* - function calls within each function
*
* Code modified from https://convincedcoder.com/2019/01/19/Processing-TypeScript-using-TypeScript/
* @param node
* @param sourceFile
* @param indentLevel -- helpful for logging
*/
function extractFunctionCalls(node: ts.Node, sourceFile: ts.SourceFile, indentLevel: number) {
// e.g `function hello()`
if (ts.isFunctionDeclaration(node)) {
node.forEachChild(child => {
if (ts.isIdentifier(child)) {
const declaredFunction: string = child.getText(sourceFile);
updateDeclaredFunctions(declaredFunction);
}
});
}
// Arrow function
if (
ts.isVariableDeclaration(node) &&
node.initializer &&
ts.isArrowFunction(node.initializer) &&
indentLevel === 3
) {
const child = node.getChildAt(0, sourceFile);
if (ts.isIdentifier(child)) {
const declaredFunction: string = child.getText(sourceFile);
updateDeclaredFunctions(declaredFunction);
}
}
// First child must be `Identifier`
// examples of what gets skipped: `fs.readFile('lol.json')` or `ipc.on('something', () => {})`
if (ts.isCallExpression(node)) {
const child = node.getChildAt(0, sourceFile);
if (ts.isIdentifier(child)) {
const calledFunction: string = child.getText(sourceFile);
updateCalledFunctions(calledFunction);
}
}
// logNode(node, sourceFile, indentLevel);
node.forEachChild(child => extractFunctionCalls(child, sourceFile, indentLevel + 1));
}
/**
* Log stuff if needed
* @param node
* @param sourceFile
* @param indentLevel
*/
function logNode(node: ts.Node, sourceFile: ts.SourceFile, indentLevel: number) {
const indentation = "-".repeat(indentLevel);
const syntaxKind = ts.SyntaxKind[node.kind];
const nodeText = node.getText(sourceFile).split('\n')[0];
console.log(`${indentation}${syntaxKind}: ${nodeText}`);
}
/**
* Update `allFunctions` and `currentFunction`
* @param declaredFunction
*/
function updateDeclaredFunctions(declaredFunction: string): void {
currentFunction = declaredFunction;
allFunctions.push(declaredFunction);
}
/**
* Update `calledFunctions` map with current called function name
* @param calledFunction - name of the function getting called
*/
function updateCalledFunctions(calledFunction: string): void {
if (!functionsToIgnore.includes(calledFunction)) {
if (calledFunctions.has(currentFunction)) {
const pastCalls = calledFunctions.get(currentFunction);
pastCalls.push(calledFunction);
calledFunctions.set(currentFunction, pastCalls);
} else {
calledFunctions.set(currentFunction, [calledFunction]);
}
}
}
export function processFiles(filenames: string[]) {
// =================================================================================================
// instead of: extractFunctionCalls(sourceFile, 0, sourceFile);
// grab all the root nodes first
// then do recursion for each
filenames.forEach((filename) => {
const rootNodes: ts.Node[] = [];
let codeAsString: string;
let skipFile: boolean = false;
try {
codeAsString = fs.readFileSync(filename).toString();
} catch (err) {
console.log('File', green(filename), red('not found!'), ' - skipping');
skipFile = true;
}
if (!skipFile) {
const sourceFile: ts.SourceFile = ts.createSourceFile(filename, codeAsString, ts.ScriptTarget.Latest);
sourceFile.forEachChild((child: ts.Node) => {
rootNodes.push(child)
});
rootNodes.forEach((node: ts.Node) => {
currentFunction = undefined;
extractFunctionCalls(node, sourceFile, 1);
});
}
});
calledFunctions.delete(undefined);
// Output
console.log('');
console.log('======================================');
console.log(allFunctions);
console.log('--------------------------------------');
console.log(calledFunctions);
console.log('--------------------------------------');
console.log('Functions: \t\t\t', allFunctions.length);
console.log('Functions that call others: \t', calledFunctions.size);
console.log('--------------------------------------');
// Only include functions that exist in the `allFunctions` list
calledFunctions.forEach((value, key) => {
calledFunctions.set(key, value.filter((calledFunc: string) => {
return allFunctions.includes(calledFunc);
}));
if (!calledFunctions.get(key).length) {
calledFunctions.delete(key);
}
});
console.log(calledFunctions);
const functions = {
all: allFunctions,
called: calledFunctions,
}
return functions;
}