forked from typescript-eslint/typescript-eslint
/
useProvidedProgram.ts
80 lines (70 loc) · 2.34 KB
/
useProvidedProgram.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import debug from 'debug';
import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
import { Extra } from '../parser-options';
import { ASTAndProgram, getAstFromProgram } from './shared';
const log = debug('typescript-eslint:typescript-estree:useProvidedProgram');
function useProvidedProgram(
programInstance: ts.Program,
extra: Extra,
): ASTAndProgram | undefined {
log('Retrieving ast for %s from provided program instance', extra.filePath);
programInstance.getTypeChecker(); // ensure parent pointers are set in source files
const astAndProgram = getAstFromProgram(programInstance, extra);
if (!astAndProgram) {
const relativeFilePath = path.relative(
extra.tsconfigRootDir || process.cwd(),
extra.filePath,
);
const errorLines = [
'"parserOptions.program" has been provided for @typescript-eslint/parser.',
`The file was not found in the provided program instance: ${relativeFilePath}`,
];
throw new Error(errorLines.join('\n'));
}
return astAndProgram;
}
/**
* Utility offered by parser to help consumers construct their own program instance.
*/
function createProgramFromConfigFile(
configFile: string,
projectDirectory: string = path.dirname(configFile),
): ts.Program {
const config = ts.readConfigFile(configFile, ts.sys.readFile);
if (config.error !== undefined) {
throw new Error(
ts.formatDiagnostics([config.error], {
getCanonicalFileName: f => f,
getCurrentDirectory: process.cwd,
getNewLine: () => '\n',
}),
);
}
const parseConfigHost: ts.ParseConfigHost = {
fileExists: fs.existsSync,
readDirectory: ts.sys.readDirectory,
readFile: file => fs.readFileSync(file, 'utf8'),
useCaseSensitiveFileNames: true,
};
const parsed = ts.parseJsonConfigFileContent(
config.config,
parseConfigHost,
path.resolve(projectDirectory),
{ noEmit: true },
);
if (parsed.errors.length) {
throw new Error(
ts.formatDiagnostics(parsed.errors, {
getCanonicalFileName: f => f,
getCurrentDirectory: process.cwd,
getNewLine: () => '\n',
}),
);
}
const host = ts.createCompilerHost(parsed.options, true);
const program = ts.createProgram(parsed.fileNames, parsed.options, host);
return program;
}
export { useProvidedProgram, createProgramFromConfigFile };