-
Notifications
You must be signed in to change notification settings - Fork 1
/
NodePrinter.ts
64 lines (52 loc) · 1.53 KB
/
NodePrinter.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
// tslint:disable-next-line: no-implicit-dependencies
import { createPrinter, createSourceFile, EmitHint, NewLineKind, Node, Printer, ScriptKind, ScriptTarget, SourceFile } from 'typescript';
import { NodeBuilder } from './NodeBuilder';
export class NodePrinter {
printer: Printer;
tempFile: SourceFile;
static printNode(node: Node | Node[] | NodeBuilder): string {
let nodesToPrint: Node | Node[];
if (node instanceof NodeBuilder) {
nodesToPrint = node.nodes;
} else {
nodesToPrint = node;
}
const printer = new NodePrinter();
return printer.printNode(nodesToPrint);
}
printNode(node: Node | Node[]): string {
if (this.printer === undefined) {
this.initializePrinter();
}
if (node === undefined) {
return '';
}
if (Array.isArray(node)) {
if (node.length < 1) {
return '';
}
const result: string[] = [];
node.forEach(item => {
result.push(this.printer.printNode(EmitHint.Unspecified, item, this.tempFile));
});
// return this.printer.printList(ListFormat.SourceFileStatements, createNodeArray(node), this.tempFile);
return result.join('\n');
} else {
return this.printer.printNode(EmitHint.Unspecified, node, this.tempFile);
}
}
initializePrinter(): void {
this.tempFile = createSourceFile(
'tmp.ts',
'',
ScriptTarget.Latest,
false,
ScriptKind.TS
);
this.printer = createPrinter(
{
newLine: NewLineKind.CarriageReturnLineFeed
}
);
}
}