Skip to content

Commit

Permalink
refactor: update reportCompileDiagnostic to include source code context
Browse files Browse the repository at this point in the history
  • Loading branch information
steven-pribilinskiy committed Oct 14, 2024
1 parent 459fb3c commit f8b7937
Showing 1 changed file with 30 additions and 5 deletions.
35 changes: 30 additions & 5 deletions src/compileTypes/helpers/reportCompileDiagnostic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,38 @@ import ts from 'typescript';
import { getLogger } from '../../helpers';
import type { CommonLogger } from '../../models';

const CONTEXT_LINES = 3;

export function reportCompileDiagnostic(
diagnostic: ts.Diagnostic,
logger: CommonLogger = getLogger(),
): void {
const { line } = diagnostic.file!.getLineAndCharacterOfPosition(diagnostic.start!);
logger.log(
`TS Error ${diagnostic.code}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine)}`,
);
logger.log(` at ${diagnostic.file!.fileName}:${line + 1}`);
const message = [
`TS Error ${diagnostic.code}:`,
ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine),
].join(' ');

if (diagnostic.file && diagnostic.start !== undefined) {
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
const sourceCode = diagnostic.file.text;
const lines = sourceCode.split('\n');

const startLine = Math.max(0, line - CONTEXT_LINES);
const endLine = Math.min(lines.length - 1, line + CONTEXT_LINES);

logger.error(message);
logger.error(` at ${diagnostic.file.fileName}:${line + 1}:${character + 1}`);

for (let i = startLine; i <= endLine; i++) {
const prefix = i === line ? '> ' : ' ';
logger.error(`${prefix}${i + 1} | ${lines[i]}`);

if (i === line) {
const caretPosition = prefix.length + (i + 1).toString().length + 3 + character;
logger.error(`${' '.repeat(caretPosition)}^`);
}
}
} else {
logger.error(message);
}
}

0 comments on commit f8b7937

Please sign in to comment.