|
| 1 | +import * as ts from "typescript"; |
| 2 | +import * as path from "path"; |
| 3 | + |
| 4 | +import { BaseError } from "../Error/BaseError"; |
| 5 | +import { DiagnosticError } from "../Error/DiagnosticError"; |
| 6 | +import { UnknownNodeError } from "../Error/UnknownNodeError"; |
| 7 | + |
| 8 | +function getSourceFile(node: ts.Node): ts.SourceFile { |
| 9 | + let sourceFile: ts.Node = node.parent; |
| 10 | + while (sourceFile) { |
| 11 | + if (sourceFile.kind === ts.SyntaxKind.SourceFile) { |
| 12 | + return sourceFile as ts.SourceFile; |
| 13 | + } |
| 14 | + sourceFile = sourceFile.parent; |
| 15 | + } |
| 16 | + |
| 17 | + return undefined; |
| 18 | +} |
| 19 | + |
| 20 | +function getNodeLocation(node: ts.Node): [string, number, number] { |
| 21 | + const sourceFile: ts.SourceFile = getSourceFile(node); |
| 22 | + if (!sourceFile) { |
| 23 | + return ["<unknown file>", 0, 0]; |
| 24 | + } |
| 25 | + |
| 26 | + const lineAndChar: ts.LineAndCharacter = ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile)); |
| 27 | + return [sourceFile.fileName, lineAndChar.line + 1, lineAndChar.character]; |
| 28 | +} |
| 29 | + |
| 30 | +export function formatError(error: BaseError): string { |
| 31 | + if (error instanceof DiagnosticError) { |
| 32 | + const rootDir: string = process.cwd().split(path.sep)[0] || "/"; |
| 33 | + return ts.formatDiagnostics(error.getDiagnostics(), { |
| 34 | + getCanonicalFileName: (fileName: string) => fileName, |
| 35 | + getCurrentDirectory: () => rootDir, |
| 36 | + getNewLine: () => "\n", |
| 37 | + }); |
| 38 | + } else if (error instanceof UnknownNodeError) { |
| 39 | + const firstLine: string = error.getNode().getFullText().trim().split("\n")[0].trim(); |
| 40 | + const [sourceFile, lineNumber, charPos]: [string, number, number] = getNodeLocation(error.getNode()); |
| 41 | + return `${error.name}: Unknown node type "${firstLine}" at ${sourceFile}(${lineNumber},${charPos})\n`; |
| 42 | + } |
| 43 | + |
| 44 | + return `${error.name}: ${error.message}\n`; |
| 45 | +} |
0 commit comments