Skip to content

Commit f8b7937

Browse files
refactor: update reportCompileDiagnostic to include source code context
1 parent 459fb3c commit f8b7937

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

src/compileTypes/helpers/reportCompileDiagnostic.ts

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,38 @@ import ts from 'typescript';
33
import { getLogger } from '../../helpers';
44
import type { CommonLogger } from '../../models';
55

6+
const CONTEXT_LINES = 3;
7+
68
export function reportCompileDiagnostic(
79
diagnostic: ts.Diagnostic,
810
logger: CommonLogger = getLogger(),
911
): void {
10-
const { line } = diagnostic.file!.getLineAndCharacterOfPosition(diagnostic.start!);
11-
logger.log(
12-
`TS Error ${diagnostic.code}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine)}`,
13-
);
14-
logger.log(` at ${diagnostic.file!.fileName}:${line + 1}`);
12+
const message = [
13+
`TS Error ${diagnostic.code}:`,
14+
ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine),
15+
].join(' ');
16+
17+
if (diagnostic.file && diagnostic.start !== undefined) {
18+
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
19+
const sourceCode = diagnostic.file.text;
20+
const lines = sourceCode.split('\n');
21+
22+
const startLine = Math.max(0, line - CONTEXT_LINES);
23+
const endLine = Math.min(lines.length - 1, line + CONTEXT_LINES);
24+
25+
logger.error(message);
26+
logger.error(` at ${diagnostic.file.fileName}:${line + 1}:${character + 1}`);
27+
28+
for (let i = startLine; i <= endLine; i++) {
29+
const prefix = i === line ? '> ' : ' ';
30+
logger.error(`${prefix}${i + 1} | ${lines[i]}`);
31+
32+
if (i === line) {
33+
const caretPosition = prefix.length + (i + 1).toString().length + 3 + character;
34+
logger.error(`${' '.repeat(caretPosition)}^`);
35+
}
36+
}
37+
} else {
38+
logger.error(message);
39+
}
1540
}

0 commit comments

Comments
 (0)