UNPKG

1.71 kBPlain TextView Raw
1import {
2 Diagnostic,
3 formatDiagnostics,
4 FormatDiagnosticsHost,
5 sys,
6} from "typescript";
7import { getCanonicalFileName } from "./fs/path-utils";
8import {
9 AbsolutePath,
10 DiagnosticsHandler,
11 NormalizedOptions,
12} from "./interfaces";
13
14export default class DiagnosticsHandlerImpl implements DiagnosticsHandler {
15 private throwOnError: boolean;
16 private host: FormatDiagnosticsHost;
17 private write = sys.write;
18
19 constructor(options: NormalizedOptions) {
20 this.throwOnError = options.throwOnError;
21 this.host = createFormatDiagnosticsHost(options.workingPath);
22 }
23
24 public setWrite(write: (s: string) => void) {
25 this.write = write;
26 }
27
28 public check(
29 diagnostics: Diagnostic | Diagnostic[] | undefined,
30 throwOnError?: boolean
31 ): boolean {
32 const normalized = normalize(diagnostics);
33 if (normalized === undefined) {
34 return false;
35 }
36 const message = this.format(normalized);
37 if (this.throwOnError || throwOnError === true) {
38 throw new Error(message);
39 }
40 this.write(message);
41 return true;
42 }
43
44 public format(diagnostics: Diagnostic[]) {
45 return formatDiagnostics(diagnostics, this.host);
46 }
47}
48
49function normalize(
50 diagnostics: Diagnostic | Diagnostic[] | undefined
51): Diagnostic[] | undefined {
52 if (diagnostics === undefined) {
53 return undefined;
54 }
55 if (Array.isArray(diagnostics)) {
56 return diagnostics.length === 0 ? undefined : diagnostics;
57 }
58 return [diagnostics];
59}
60
61function createFormatDiagnosticsHost(
62 rootPath: AbsolutePath
63): FormatDiagnosticsHost {
64 const newLine = sys.newLine;
65
66 return {
67 getCanonicalFileName,
68 getCurrentDirectory: () => rootPath,
69 getNewLine: () => newLine,
70 };
71}