-
Notifications
You must be signed in to change notification settings - Fork 1
/
SourceAnalyser.ts
69 lines (52 loc) · 1.98 KB
/
SourceAnalyser.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
// tslint:disable-next-line: max-line-length
import { ClassDeclaration, createImportDeclaration, createSourceFile, createStringLiteral, ImportDeclaration, Node, ScriptTarget, SyntaxKind } from 'typescript';
import { SourceFileDescriptor } from '../descriptors/SourceFileDescriptor';
import { ClassAnalyer } from './ClassAnalyer';
export class SourceAnalyser {
analyse(sourceFilePath: string, sourceFileContent: string): SourceFileDescriptor {
const fd = new SourceFileDescriptor(sourceFilePath);
// tslint:disable-next-line: non-literal-fs-path
fd.sourceFileContent = sourceFileContent;
const sourceFile = createSourceFile(fd.sourceFilePath, fd.sourceFileContent, ScriptTarget.Latest, true);
const syntaxList = sourceFile
.getChildren()
.find(item => item.kind === SyntaxKind.SyntaxList);
fd.syntaxList = syntaxList;
fd.importClause = syntaxList
.getChildren()
.filter(item => item.kind === SyntaxKind.ImportDeclaration);
fd.classDeclarations = syntaxList
.getChildren()
.filter(item => item.kind === SyntaxKind.ClassDeclaration);
if (fd.isSourceValid()) {
// imports
const imports = this.getImports(fd.importClause);
fd.importDeclarations = imports;
// Get all class declarations
fd.classDeclarations.forEach(c => {
const ca = new ClassAnalyer();
const ifd = ca.getClassDescriptor(<ClassDeclaration>c);
fd.classDescriptors.push(ifd);
});
} else {
throw new Error('Invalid source file!');
}
return fd;
// this.visit(sourceFile);
}
getImports(importClause: Node[]): ImportDeclaration[] {
return importClause.map(item => {
const id = <ImportDeclaration>item;
const name = id.moduleSpecifier
.getText()
.replace(/\'/gm, '')
.replace(/\"/gm, '');
return createImportDeclaration(
id.decorators,
id.modifiers,
id.importClause,
createStringLiteral(name)
);
});
}
}