forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
useProgramFromProjectService.ts
63 lines (54 loc) · 2.09 KB
/
useProgramFromProjectService.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
import { minimatch } from 'minimatch';
import path from 'path';
import { createProjectProgram } from './create-program/createProjectProgram';
import type { ProjectServiceSettings } from './create-program/createProjectService';
import { type ASTAndDefiniteProgram } from './create-program/shared';
import type { MutableParseSettings } from './parseSettings';
export function useProgramFromProjectService(
{ allowDefaultProjectForFiles, service }: ProjectServiceSettings,
parseSettings: Readonly<MutableParseSettings>,
hasFullTypeInformation: boolean,
): ASTAndDefiniteProgram | undefined {
const filePath = absolutify(parseSettings.filePath);
const opened = service.openClientFile(
filePath,
parseSettings.codeFullText,
/* scriptKind */ undefined,
parseSettings.tsconfigRootDir,
);
if (hasFullTypeInformation) {
if (opened.configFileName) {
if (filePathMatchedBy(filePath, allowDefaultProjectForFiles)) {
throw new Error(
`${filePath} was included by allowDefaultProjectForFiles but also was found in the project service. Consider removing it from allowDefaultProjectForFiles.`,
);
}
} else if (!filePathMatchedBy(filePath, allowDefaultProjectForFiles)) {
throw new Error(
`${filePath} was not found by the project service. Consider either including it in the tsconfig.json or including it in allowDefaultProjectForFiles.`,
);
}
}
const scriptInfo = service.getScriptInfo(filePath);
const program = service
.getDefaultProjectForFile(scriptInfo!.fileName, true)!
.getLanguageService(/*ensureSynchronized*/ true)
.getProgram();
if (!program) {
return undefined;
}
return createProjectProgram(parseSettings, [program]);
function absolutify(filePath: string): string {
return path.isAbsolute(filePath)
? filePath
: path.join(service.host.getCurrentDirectory(), filePath);
}
}
function filePathMatchedBy(
filePath: string,
allowDefaultProjectForFiles: string[] | undefined,
): boolean {
return !!allowDefaultProjectForFiles?.some(pattern =>
minimatch(filePath, pattern),
);
}