forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
createDefaultProgram.ts
69 lines (56 loc) · 1.82 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
63
64
65
66
67
68
69
import debug from 'debug';
import path from 'path';
import * as ts from 'typescript';
import type { ParseSettings } from '../parseSettings';
import type { ASTAndProgram } from './shared';
import {
createDefaultCompilerOptionsFromExtra,
getModuleResolver,
} from './shared';
const log = debug('typescript-eslint:typescript-estree:createDefaultProgram');
/**
* @param parseSettings Internal settings for parsing the file
* @returns If found, returns the source file corresponding to the code and the containing program
*/
function createDefaultProgram(
parseSettings: ParseSettings,
): ASTAndProgram | undefined {
log(
'Getting default program for: %s',
parseSettings.filePath || 'unnamed file',
);
if (parseSettings.projects?.length !== 1) {
return undefined;
}
const tsconfigPath = parseSettings.projects[0];
const commandLine = ts.getParsedCommandLineOfConfigFile(
tsconfigPath,
createDefaultCompilerOptionsFromExtra(parseSettings),
{ ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} },
);
if (!commandLine) {
return undefined;
}
const compilerHost = ts.createCompilerHost(
commandLine.options,
/* setParentNodes */ true,
);
if (parseSettings.moduleResolver) {
compilerHost.resolveModuleNames = getModuleResolver(
parseSettings.moduleResolver,
).resolveModuleNames;
}
const oldReadFile = compilerHost.readFile;
compilerHost.readFile = (fileName: string): string | undefined =>
path.normalize(fileName) === path.normalize(parseSettings.filePath)
? parseSettings.code
: oldReadFile(fileName);
const program = ts.createProgram(
[parseSettings.filePath],
commandLine.options,
compilerHost,
);
const ast = program.getSourceFile(parseSettings.filePath);
return ast && { ast, program };
}
export { createDefaultProgram };