/
createDefaultProgram.ts
62 lines (52 loc) · 1.71 KB
/
createDefaultProgram.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
import debug from 'debug';
import path from 'path';
import * as ts from 'typescript';
import { Extra } from '../parser-options';
import {
ASTAndProgram,
CanonicalPath,
createDefaultCompilerOptionsFromExtra,
} from './shared';
const log = debug('typescript-eslint:typescript-estree:createDefaultProgram');
/**
* @param code The code of the file being linted
* @param extra The config object
* @param extra.tsconfigRootDir The root directory for relative tsconfig paths
* @param extra.projects Provided tsconfig paths
* @returns If found, returns the source file corresponding to the code and the containing program
*/
function createDefaultProgram(
code: string,
extra: Extra,
): ASTAndProgram | undefined {
log('Getting default program for: %s', extra.filePath || 'unnamed file');
if (!extra.projects || extra.projects.length !== 1) {
return undefined;
}
const tsconfigPath: CanonicalPath = extra.projects[0];
const commandLine = ts.getParsedCommandLineOfConfigFile(
tsconfigPath,
createDefaultCompilerOptionsFromExtra(extra),
{ ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} },
);
if (!commandLine) {
return undefined;
}
const compilerHost = ts.createCompilerHost(
commandLine.options,
/* setParentNodes */ true,
);
const oldReadFile = compilerHost.readFile;
compilerHost.readFile = (fileName: string): string | undefined =>
path.normalize(fileName) === path.normalize(extra.filePath)
? code
: oldReadFile(fileName);
const program = ts.createProgram(
[extra.filePath],
commandLine.options,
compilerHost,
);
const ast = program.getSourceFile(extra.filePath);
return ast && { ast, program };
}
export { createDefaultProgram };