-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
service.ts
1419 lines (1223 loc) · 54.7 KB
/
service.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* service.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* Author: Eric Traut
*
* A persistent service that is able to analyze a collection of
* Python files.
*/
import * as TOML from '@iarna/toml';
import * as JSONC from 'jsonc-parser';
import {
AbstractCancellationTokenSource,
CancellationToken,
CompletionItem,
DocumentSymbol,
} from 'vscode-languageserver';
import { TextDocumentContentChangeEvent } from 'vscode-languageserver-textdocument';
import {
CallHierarchyIncomingCall,
CallHierarchyItem,
CallHierarchyOutgoingCall,
DocumentHighlight,
MarkupKind,
} from 'vscode-languageserver-types';
import { BackgroundAnalysisBase } from '../backgroundAnalysisBase';
import { createBackgroundThreadCancellationTokenSource } from '../common/cancellationUtils';
import { CommandLineOptions } from '../common/commandLineOptions';
import { ConfigOptions } from '../common/configOptions';
import { ConsoleInterface, log, LogLevel, StandardConsole } from '../common/console';
import { Diagnostic } from '../common/diagnostic';
import { FileEditAction, TextEditAction } from '../common/editAction';
import { LanguageServiceExtension } from '../common/extensibility';
import { FileSystem, FileWatcher, ignoredWatchEventFunction } from '../common/fileSystem';
import {
combinePaths,
FileSpec,
forEachAncestorDirectory,
getDirectoryPath,
getFileName,
getFileSpec,
getFileSystemEntries,
isDirectory,
normalizePath,
stripFileExtension,
tryRealpath,
tryStat,
} from '../common/pathUtils';
import { DocumentRange, Position, Range } from '../common/textRange';
import { timingStats } from '../common/timing';
import { AbbreviationMap, CompletionOptions, CompletionResults } from '../languageService/completionProvider';
import { DefinitionFilter } from '../languageService/definitionProvider';
import { IndexResults, WorkspaceSymbolCallback } from '../languageService/documentSymbolProvider';
import { HoverResults } from '../languageService/hoverProvider';
import { ReferenceCallback } from '../languageService/referencesProvider';
import { SignatureHelpResults } from '../languageService/signatureHelpProvider';
import { AnalysisCompleteCallback } from './analysis';
import { BackgroundAnalysisProgram, BackgroundAnalysisProgramFactory } from './backgroundAnalysisProgram';
import { ImportedModuleDescriptor, ImportResolver, ImportResolverFactory } from './importResolver';
import { MaxAnalysisTime } from './program';
import { findPythonSearchPaths } from './pythonPathUtils';
import { TypeEvaluator } from './typeEvaluator';
export const configFileNames = ['pyrightconfig.json', 'mspythonconfig.json'];
export const pyprojectTomlName = 'pyproject.toml';
// How long since the last user activity should we wait until running
// the analyzer on any files that have not yet been analyzed?
const _userActivityBackoffTimeInMs = 250;
export class AnalyzerService {
private _instanceName: string;
private _importResolverFactory: ImportResolverFactory;
private _executionRootPath: string;
private _typeStubTargetPath: string | undefined;
private _typeStubTargetIsSingleFile = false;
private _console: ConsoleInterface;
private _sourceFileWatcher: FileWatcher | undefined;
private _reloadConfigTimer: any;
private _libraryReanalysisTimer: any;
private _configFilePath: string | undefined;
private _configFileWatcher: FileWatcher | undefined;
private _libraryFileWatcher: FileWatcher | undefined;
private _onCompletionCallback: AnalysisCompleteCallback | undefined;
private _commandLineOptions: CommandLineOptions | undefined;
private _analyzeTimer: any;
private _requireTrackedFileUpdate = true;
private _lastUserInteractionTime = Date.now();
private _extension: LanguageServiceExtension | undefined;
private _backgroundAnalysisProgram: BackgroundAnalysisProgram;
private _backgroundAnalysisCancellationSource: AbstractCancellationTokenSource | undefined;
private _maxAnalysisTimeInForeground?: MaxAnalysisTime;
private _backgroundAnalysisProgramFactory?: BackgroundAnalysisProgramFactory;
private _disposed = false;
constructor(
instanceName: string,
fs: FileSystem,
console?: ConsoleInterface,
importResolverFactory?: ImportResolverFactory,
configOptions?: ConfigOptions,
extension?: LanguageServiceExtension,
backgroundAnalysis?: BackgroundAnalysisBase,
maxAnalysisTime?: MaxAnalysisTime,
backgroundAnalysisProgramFactory?: BackgroundAnalysisProgramFactory
) {
this._instanceName = instanceName;
this._console = console || new StandardConsole();
this._executionRootPath = '';
this._extension = extension;
this._importResolverFactory = importResolverFactory || AnalyzerService.createImportResolver;
this._maxAnalysisTimeInForeground = maxAnalysisTime;
this._backgroundAnalysisProgramFactory = backgroundAnalysisProgramFactory;
configOptions = configOptions ?? new ConfigOptions(process.cwd());
const importResolver = this._importResolverFactory(fs, configOptions);
this._backgroundAnalysisProgram =
backgroundAnalysisProgramFactory !== undefined
? backgroundAnalysisProgramFactory(
this._console,
configOptions,
importResolver,
this._extension,
backgroundAnalysis,
this._maxAnalysisTimeInForeground
)
: new BackgroundAnalysisProgram(
this._console,
configOptions,
importResolver,
this._extension,
backgroundAnalysis,
this._maxAnalysisTimeInForeground
);
}
clone(instanceName: string, backgroundAnalysis?: BackgroundAnalysisBase): AnalyzerService {
return new AnalyzerService(
instanceName,
this._fs,
this._console,
this._importResolverFactory,
this._backgroundAnalysisProgram.configOptions,
this._extension,
backgroundAnalysis,
this._maxAnalysisTimeInForeground,
this._backgroundAnalysisProgramFactory
);
}
dispose() {
this._disposed = true;
this._removeSourceFileWatchers();
this._removeConfigFileWatcher();
this._removeLibraryFileWatcher();
this._clearReloadConfigTimer();
this._clearReanalysisTimer();
this._clearLibraryReanalysisTimer();
}
get backgroundAnalysisProgram(): BackgroundAnalysisProgram {
return this._backgroundAnalysisProgram;
}
static createImportResolver(fs: FileSystem, options: ConfigOptions): ImportResolver {
return new ImportResolver(fs, options);
}
setCompletionCallback(callback: AnalysisCompleteCallback | undefined): void {
this._onCompletionCallback = callback;
this._backgroundAnalysisProgram.setCompletionCallback(callback);
}
setOptions(commandLineOptions: CommandLineOptions, reanalyze = true): void {
this._commandLineOptions = commandLineOptions;
const configOptions = this._getConfigOptions(commandLineOptions);
if (configOptions.pythonPath) {
// Make sure we have default python environment set.
configOptions.ensureDefaultPythonVersion(configOptions.pythonPath, this._console);
}
configOptions.ensureDefaultPythonPlatform(this._console);
this._backgroundAnalysisProgram.setConfigOptions(configOptions);
this._executionRootPath = normalizePath(
combinePaths(commandLineOptions.executionRoot, configOptions.projectRoot)
);
this._applyConfigOptions(reanalyze);
}
setFileOpened(path: string, version: number | null, contents: string) {
this._backgroundAnalysisProgram.setFileOpened(path, version, contents);
this._scheduleReanalysis(false);
}
updateOpenFileContents(path: string, version: number | null, contents: TextDocumentContentChangeEvent[]) {
this._backgroundAnalysisProgram.updateOpenFileContents(path, version, contents);
this._scheduleReanalysis(false);
}
test_setIndexing(
workspaceIndices: Map<string, IndexResults>,
libraryIndices: Map<string, Map<string, IndexResults>>
) {
this._backgroundAnalysisProgram.test_setIndexing(workspaceIndices, libraryIndices);
}
startIndexing() {
this._backgroundAnalysisProgram.startIndexing();
}
setFileClosed(path: string) {
this._backgroundAnalysisProgram.setFileClosed(path);
this._scheduleReanalysis(false);
}
getParseResult(path: string) {
return this._program.getBoundSourceFile(path)?.getParseResults();
}
getTextOnRange(filePath: string, range: Range, token: CancellationToken) {
return this._program.getTextOnRange(filePath, range, token);
}
getAutoImports(
filePath: string,
range: Range,
similarityLimit: number,
nameMap: AbbreviationMap | undefined,
lazyEdit: boolean,
allowVariableInAll: boolean,
token: CancellationToken
) {
return this._program.getAutoImports(
filePath,
range,
similarityLimit,
nameMap,
this._backgroundAnalysisProgram.getIndexing(filePath),
lazyEdit,
allowVariableInAll,
token
);
}
getDefinitionForPosition(
filePath: string,
position: Position,
filter: DefinitionFilter,
token: CancellationToken
): DocumentRange[] | undefined {
return this._program.getDefinitionsForPosition(filePath, position, filter, token);
}
reportReferencesForPosition(
filePath: string,
position: Position,
includeDeclaration: boolean,
reporter: ReferenceCallback,
token: CancellationToken
) {
this._program.reportReferencesForPosition(filePath, position, includeDeclaration, reporter, token);
}
addSymbolsForDocument(filePath: string, symbolList: DocumentSymbol[], token: CancellationToken) {
this._program.addSymbolsForDocument(filePath, symbolList, token);
}
reportSymbolsForWorkspace(query: string, reporter: WorkspaceSymbolCallback, token: CancellationToken) {
this._program.reportSymbolsForWorkspace(query, reporter, token);
}
getHoverForPosition(
filePath: string,
position: Position,
format: MarkupKind,
token: CancellationToken
): HoverResults | undefined {
return this._program.getHoverForPosition(filePath, position, format, token);
}
getDocumentHighlight(
filePath: string,
position: Position,
token: CancellationToken
): DocumentHighlight[] | undefined {
return this._program.getDocumentHighlight(filePath, position, token);
}
getSignatureHelpForPosition(
filePath: string,
position: Position,
format: MarkupKind,
token: CancellationToken
): SignatureHelpResults | undefined {
return this._program.getSignatureHelpForPosition(filePath, position, format, token);
}
getCompletionsForPosition(
filePath: string,
position: Position,
workspacePath: string,
options: CompletionOptions,
nameMap: AbbreviationMap | undefined,
token: CancellationToken
): Promise<CompletionResults | undefined> {
return this._program.getCompletionsForPosition(
filePath,
position,
workspacePath,
options,
nameMap,
this._backgroundAnalysisProgram.getIndexing(filePath),
token
);
}
getEvaluator(): TypeEvaluator | undefined {
return this._program.evaluator;
}
resolveCompletionItem(
filePath: string,
completionItem: CompletionItem,
options: CompletionOptions,
nameMap: AbbreviationMap | undefined,
token: CancellationToken
) {
this._program.resolveCompletionItem(
filePath,
completionItem,
options,
nameMap,
this._backgroundAnalysisProgram.getIndexing(filePath),
token
);
}
performQuickAction(
filePath: string,
command: string,
args: any[],
token: CancellationToken
): TextEditAction[] | undefined {
return this._program.performQuickAction(filePath, command, args, token);
}
renameSymbolAtPosition(
filePath: string,
position: Position,
newName: string,
token: CancellationToken
): FileEditAction[] | undefined {
return this._program.renameSymbolAtPosition(filePath, position, newName, token);
}
getCallForPosition(filePath: string, position: Position, token: CancellationToken): CallHierarchyItem | undefined {
return this._program.getCallForPosition(filePath, position, token);
}
getIncomingCallsForPosition(
filePath: string,
position: Position,
token: CancellationToken
): CallHierarchyIncomingCall[] | undefined {
return this._program.getIncomingCallsForPosition(filePath, position, token);
}
getOutgoingCallsForPosition(
filePath: string,
position: Position,
token: CancellationToken
): CallHierarchyOutgoingCall[] | undefined {
return this._program.getOutgoingCallsForPosition(filePath, position, token);
}
printStats() {
this._console.info('');
this._console.info('Analysis stats');
const fileCount = this._program.getFileCount();
this._console.info('Total files analyzed: ' + fileCount.toString());
}
printDependencies(verbose: boolean) {
this._program.printDependencies(this._executionRootPath, verbose);
}
getDiagnosticsForRange(filePath: string, range: Range, token: CancellationToken): Promise<Diagnostic[]> {
return this._backgroundAnalysisProgram.getDiagnosticsForRange(filePath, range, token);
}
getConfigOptions() {
return this._configOptions;
}
getImportResolver(): ImportResolver {
return this._backgroundAnalysisProgram.importResolver;
}
recordUserInteractionTime() {
this._lastUserInteractionTime = Date.now();
// If we have a pending timer for reanalysis, cancel it
// and reschedule for some time in the future.
if (this._analyzeTimer) {
this._scheduleReanalysis(false);
}
}
// test only APIs
get test_program() {
return this._program;
}
test_getConfigOptions(commandLineOptions: CommandLineOptions): ConfigOptions {
return this._getConfigOptions(commandLineOptions);
}
test_getFileNamesFromFileSpecs(): string[] {
return this._getFileNamesFromFileSpecs();
}
// Calculates the effective options based on the command-line options,
// an optional config file, and default values.
private _getConfigOptions(commandLineOptions: CommandLineOptions): ConfigOptions {
let projectRoot = commandLineOptions.executionRoot;
let configFilePath: string | undefined;
let pyprojectFilePath: string | undefined;
if (commandLineOptions.configFilePath) {
// If the config file path was specified, determine whether it's
// a directory (in which case the default config file name is assumed)
// or a file.
configFilePath = combinePaths(
commandLineOptions.executionRoot,
normalizePath(commandLineOptions.configFilePath)
);
if (!this._fs.existsSync(configFilePath)) {
this._console.info(`Configuration file not found at ${configFilePath}.`);
configFilePath = commandLineOptions.executionRoot;
} else {
if (configFilePath.toLowerCase().endsWith('.json')) {
projectRoot = getDirectoryPath(configFilePath);
} else {
projectRoot = configFilePath;
configFilePath = this._findConfigFile(configFilePath);
if (!configFilePath) {
this._console.info(`Configuration file not found at ${projectRoot}.`);
}
}
}
} else if (projectRoot) {
// In a project-based IDE like VS Code, we should assume that the
// project root directory contains the config file.
configFilePath = this._findConfigFile(projectRoot);
// If pyright is being executed from the command line, the working
// directory may be deep within a project, and we need to walk up the
// directory hierarchy to find the project root.
if (!configFilePath && !commandLineOptions.fromVsCodeExtension) {
configFilePath = this._findConfigFileHereOrUp(projectRoot);
}
if (configFilePath) {
projectRoot = getDirectoryPath(configFilePath);
} else {
this._console.info(`No configuration file found.`);
configFilePath = undefined;
}
}
if (!configFilePath) {
// See if we can find a pyproject.toml file in this directory.
pyprojectFilePath = this._findPyprojectTomlFile(projectRoot);
if (!pyprojectFilePath && !commandLineOptions.fromVsCodeExtension) {
pyprojectFilePath = this._findPyprojectTomlFileHereOrUp(projectRoot);
}
if (pyprojectFilePath) {
projectRoot = getDirectoryPath(pyprojectFilePath);
this._console.info(`pyproject.toml file found at ${projectRoot}.`);
} else {
this._console.info(`No pyproject.toml file found.`);
}
}
const configOptions = new ConfigOptions(projectRoot, this._typeCheckingMode);
const defaultExcludes = ['**/node_modules', '**/__pycache__', '.git'];
// The pythonPlatform and pythonVersion from the command-line can be overridden
// by the config file, so initialize them upfront.
configOptions.defaultPythonPlatform = commandLineOptions.pythonPlatform;
configOptions.defaultPythonVersion = commandLineOptions.pythonVersion;
configOptions.ensureDefaultExtraPaths(
this._fs,
commandLineOptions.autoSearchPaths || false,
commandLineOptions.extraPaths
);
if (commandLineOptions.fileSpecs.length > 0) {
commandLineOptions.fileSpecs.forEach((fileSpec) => {
configOptions.include.push(getFileSpec(projectRoot, fileSpec));
});
} else if (!configFilePath) {
// If no config file was found and there are no explicit include
// paths specified, assume the caller wants to include all source
// files under the execution root path.
if (commandLineOptions.executionRoot) {
configOptions.include.push(getFileSpec(commandLineOptions.executionRoot, '.'));
// Add a few common excludes to avoid long scan times.
defaultExcludes.forEach((exclude) => {
configOptions.exclude.push(getFileSpec(commandLineOptions.executionRoot, exclude));
});
}
}
this._configFilePath = configFilePath || pyprojectFilePath;
// If we found a config file, parse it to compute the effective options.
let configJsonObj: object | undefined;
if (configFilePath) {
this._console.info(`Loading configuration file at ${configFilePath}`);
configJsonObj = this._parseJsonConfigFile(configFilePath);
} else if (pyprojectFilePath) {
this._console.info(`Loading pyproject.toml file at ${pyprojectFilePath}`);
configJsonObj = this._parsePyprojectTomlFile(pyprojectFilePath);
}
if (configJsonObj) {
configOptions.initializeFromJson(
configJsonObj,
this._typeCheckingMode,
this._console,
commandLineOptions.diagnosticSeverityOverrides,
commandLineOptions.pythonPath,
commandLineOptions.fileSpecs.length > 0
);
const configFileDir = getDirectoryPath(this._configFilePath!);
// If no include paths were provided, assume that all files within
// the project should be included.
if (configOptions.include.length === 0) {
this._console.info(`No include entries specified; assuming ${configFileDir}`);
configOptions.include.push(getFileSpec(configFileDir, '.'));
}
// If there was no explicit set of excludes, add a few common ones to avoid long scan times.
if (configOptions.exclude.length === 0) {
defaultExcludes.forEach((exclude) => {
this._console.info(`Auto-excluding ${exclude}`);
configOptions.exclude.push(getFileSpec(configFileDir, exclude));
});
if (configOptions.autoExcludeVenv === undefined) {
configOptions.autoExcludeVenv = true;
}
}
} else {
configOptions.autoExcludeVenv = true;
configOptions.applyDiagnosticOverrides(commandLineOptions.diagnosticSeverityOverrides);
}
const reportDuplicateSetting = (settingName: string, configValue: number | string | boolean) => {
const settingSource = commandLineOptions.fromVsCodeExtension
? 'the client settings'
: 'a command-line option';
this._console.warn(
`The ${settingName} has been specified in both the config file and ` +
`${settingSource}. The value in the config file (${configValue}) ` +
`will take precedence`
);
};
// Apply the command-line options if the corresponding
// item wasn't already set in the config file. Report any
// duplicates.
if (commandLineOptions.venvPath) {
if (!configOptions.venvPath) {
configOptions.venvPath = commandLineOptions.venvPath;
} else {
reportDuplicateSetting('venvPath', configOptions.venvPath);
}
}
if (commandLineOptions.pythonPath) {
this._console.info(
`Setting pythonPath for service "${this._instanceName}": ` + `"${commandLineOptions.pythonPath}"`
);
configOptions.pythonPath = commandLineOptions.pythonPath;
}
if (commandLineOptions.typeshedPath) {
if (!configOptions.typeshedPath) {
configOptions.typeshedPath = commandLineOptions.typeshedPath;
} else {
reportDuplicateSetting('typeshedPath', configOptions.typeshedPath);
}
}
configOptions.verboseOutput = commandLineOptions.verboseOutput ?? configOptions.verboseOutput;
configOptions.checkOnlyOpenFiles = !!commandLineOptions.checkOnlyOpenFiles;
configOptions.autoImportCompletions = !!commandLineOptions.autoImportCompletions;
configOptions.indexing = !!commandLineOptions.indexing;
configOptions.logTypeEvaluationTime = !!commandLineOptions.logTypeEvaluationTime;
configOptions.typeEvaluationTimeThreshold = commandLineOptions.typeEvaluationTimeThreshold;
// If useLibraryCodeForTypes was not specified in the config, allow the settings
// or command line to override it.
if (configOptions.useLibraryCodeForTypes === undefined) {
configOptions.useLibraryCodeForTypes = !!commandLineOptions.useLibraryCodeForTypes;
} else if (commandLineOptions.useLibraryCodeForTypes !== undefined) {
reportDuplicateSetting('useLibraryCodeForTypes', configOptions.useLibraryCodeForTypes);
}
// If there was no stub path specified, use a default path.
if (commandLineOptions.stubPath) {
if (!configOptions.stubPath) {
configOptions.stubPath = commandLineOptions.stubPath;
} else {
reportDuplicateSetting('stubPath', configOptions.stubPath);
}
} else {
if (!configOptions.stubPath) {
configOptions.stubPath = normalizePath(combinePaths(configOptions.projectRoot, 'typings'));
}
}
// Do some sanity checks on the specified settings and report missing
// or inconsistent information.
if (configOptions.venvPath) {
if (!this._fs.existsSync(configOptions.venvPath) || !isDirectory(this._fs, configOptions.venvPath)) {
this._console.error(`venvPath ${configOptions.venvPath} is not a valid directory.`);
}
// venvPath without venv means it won't do anything while resolveImport.
// so first, try to set venv from existing configOption if it is null. if both are null,
// then, resolveImport won't consider venv
configOptions.venv = configOptions.venv ?? this._configOptions.venv;
if (configOptions.venv) {
const fullVenvPath = combinePaths(configOptions.venvPath, configOptions.venv);
if (!this._fs.existsSync(fullVenvPath) || !isDirectory(this._fs, fullVenvPath)) {
this._console.error(
`venv ${configOptions.venv} subdirectory not found in venv path ${configOptions.venvPath}.`
);
} else {
const importFailureInfo: string[] = [];
if (findPythonSearchPaths(this._fs, configOptions, importFailureInfo) === undefined) {
this._console.error(
`site-packages directory cannot be located for venvPath ` +
`${configOptions.venvPath} and venv ${configOptions.venv}.`
);
if (configOptions.verboseOutput) {
importFailureInfo.forEach((diag) => {
this._console.error(` ${diag}`);
});
}
}
}
}
}
// Is there a reference to a venv? If so, there needs to be a valid venvPath.
if (configOptions.venv) {
if (!configOptions.venvPath) {
this._console.warn(`venvPath not specified, so venv settings will be ignored.`);
}
}
if (configOptions.typeshedPath) {
if (
!this._fs.existsSync(configOptions.typeshedPath) ||
!isDirectory(this._fs, configOptions.typeshedPath)
) {
this._console.error(`typeshedPath ${configOptions.typeshedPath} is not a valid directory.`);
}
}
if (configOptions.stubPath) {
if (!this._fs.existsSync(configOptions.stubPath) || !isDirectory(this._fs, configOptions.stubPath)) {
this._console.warn(`stubPath ${configOptions.stubPath} is not a valid directory.`);
}
}
return configOptions;
}
writeTypeStub(token: CancellationToken): void {
const typingsSubdirPath = this._getTypeStubFolder();
this._program.writeTypeStub(
this._typeStubTargetPath!,
this._typeStubTargetIsSingleFile,
typingsSubdirPath,
token
);
}
writeTypeStubInBackground(token: CancellationToken): Promise<any> {
const typingsSubdirPath = this._getTypeStubFolder();
return this._backgroundAnalysisProgram.writeTypeStub(
this._typeStubTargetPath!,
this._typeStubTargetIsSingleFile,
typingsSubdirPath,
token
);
}
// This is called after a new type stub has been created. It allows
// us to invalidate caches and force reanalysis of files that potentially
// are affected by the appearance of a new type stub.
invalidateAndForceReanalysis(rebuildLibraryIndexing = true) {
// Mark all files with one or more errors dirty.
this._backgroundAnalysisProgram.invalidateAndForceReanalysis(rebuildLibraryIndexing);
}
// Forces the service to stop all analysis, discard all its caches,
// and research for files.
restart() {
this._applyConfigOptions();
this._backgroundAnalysisProgram.restart();
}
private get _fs() {
return this._backgroundAnalysisProgram.importResolver.fileSystem;
}
private get _program() {
return this._backgroundAnalysisProgram.program;
}
private get _configOptions() {
return this._backgroundAnalysisProgram.configOptions;
}
private get _watchForSourceChanges() {
return !!this._commandLineOptions?.watchForSourceChanges;
}
private get _watchForLibraryChanges() {
return !!this._commandLineOptions?.watchForLibraryChanges;
}
private get _watchForConfigChanges() {
return !!this._commandLineOptions?.watchForConfigChanges;
}
private get _typeCheckingMode() {
return this._commandLineOptions?.typeCheckingMode;
}
private get _verboseOutput(): boolean {
return !!this._configOptions.verboseOutput;
}
private get _typeStubTargetImportName() {
return this._commandLineOptions?.typeStubTargetImportName;
}
private _getTypeStubFolder() {
const stubPath = this._configOptions.stubPath;
if (!this._typeStubTargetPath || !this._typeStubTargetImportName) {
const errMsg = `Import '${this._typeStubTargetImportName}'` + ` could not be resolved`;
this._console.error(errMsg);
throw new Error(errMsg);
}
if (!stubPath) {
// We should never get here because we always generate a
// default typings path if none was specified.
const errMsg = 'No typings path was specified';
this._console.info(errMsg);
throw new Error(errMsg);
}
const typeStubInputTargetParts = this._typeStubTargetImportName.split('.');
if (typeStubInputTargetParts[0].length === 0) {
// We should never get here because the import resolution
// would have failed.
const errMsg = `Import '${this._typeStubTargetImportName}'` + ` could not be resolved`;
this._console.error(errMsg);
throw new Error(errMsg);
}
try {
// Generate a new typings directory if necessary.
if (!this._fs.existsSync(stubPath)) {
this._fs.mkdirSync(stubPath);
}
} catch (e) {
const errMsg = `Could not create typings directory '${stubPath}'`;
this._console.error(errMsg);
throw new Error(errMsg);
}
// Generate a typings subdirectory.
const typingsSubdirPath = combinePaths(stubPath, typeStubInputTargetParts[0]);
try {
// Generate a new typings subdirectory if necessary.
if (!this._fs.existsSync(typingsSubdirPath)) {
this._fs.mkdirSync(typingsSubdirPath);
}
} catch (e) {
const errMsg = `Could not create typings subdirectory '${typingsSubdirPath}'`;
this._console.error(errMsg);
throw new Error(errMsg);
}
return typingsSubdirPath;
}
private _findConfigFileHereOrUp(searchPath: string): string | undefined {
return forEachAncestorDirectory(searchPath, (ancestor) => this._findConfigFile(ancestor));
}
private _findConfigFile(searchPath: string): string | undefined {
for (const name of configFileNames) {
const fileName = combinePaths(searchPath, name);
if (this._fs.existsSync(fileName)) {
return fileName;
}
}
return undefined;
}
private _findPyprojectTomlFileHereOrUp(searchPath: string): string | undefined {
return forEachAncestorDirectory(searchPath, (ancestor) => this._findPyprojectTomlFile(ancestor));
}
private _findPyprojectTomlFile(searchPath: string) {
const fileName = combinePaths(searchPath, pyprojectTomlName);
if (this._fs.existsSync(fileName)) {
return fileName;
}
return undefined;
}
private _parseJsonConfigFile(configPath: string): object | undefined {
return this._attemptParseFile(configPath, (fileContents) => {
return JSONC.parse(fileContents);
});
}
private _parsePyprojectTomlFile(pyprojectPath: string): object | undefined {
return this._attemptParseFile(pyprojectPath, (fileContents, attemptCount) => {
try {
const configObj = TOML.parse(fileContents);
if (configObj && configObj.tool && (configObj.tool as TOML.JsonMap).pyright) {
return (configObj.tool as TOML.JsonMap).pyright as object;
}
} catch (e) {
this._console.error(`Pyproject file parse attempt ${attemptCount} error: ${JSON.stringify(e)}`);
throw e;
}
this._console.error(`Pyproject file "${pyprojectPath}" is missing "[tool.pyright] section.`);
return undefined;
});
}
private _attemptParseFile(
filePath: string,
parseCallback: (contents: string, attempt: number) => object | undefined
): object | undefined {
let fileContents = '';
let parseAttemptCount = 0;
while (true) {
// Attempt to read the file contents.
try {
fileContents = this._fs.readFileSync(filePath, 'utf8');
} catch {
this._console.error(`Config file "${filePath}" could not be read.`);
this._reportConfigParseError();
return undefined;
}
// Attempt to parse the file.
let parseFailed = false;
try {
return parseCallback(fileContents, parseAttemptCount + 1);
} catch (e) {
parseFailed = true;
}
if (!parseFailed) {
break;
}
// If we attempt to read the file immediately after it was saved, it
// may have been partially written when we read it, resulting in parse
// errors. We'll give it a little more time and try again.
if (parseAttemptCount++ >= 5) {
this._console.error(`Config file "${filePath}" could not be parsed. Verify that format is correct.`);
this._reportConfigParseError();
return undefined;
}
}
}
private _getFileNamesFromFileSpecs(): string[] {
// Use a map to generate a list of unique files.
const fileMap = new Map<string, string>();
timingStats.findFilesTime.timeOperation(() => {
const matchedFiles = this._matchFiles(this._configOptions.include, this._configOptions.exclude);
for (const file of matchedFiles) {
fileMap.set(file, file);
}
});
return [...fileMap.values()];
}
// If markFilesDirtyUnconditionally is true, we need to reparse
// and reanalyze all files in the program. If false, we will
// reparse and reanalyze only those files whose on-disk contents
// have changed. Unconditional dirtying is needed in the case where
// configuration options have changed.
private _updateTrackedFileList(markFilesDirtyUnconditionally: boolean) {
// Are we in type stub generation mode? If so, we need to search
// for a different set of files.
if (this._typeStubTargetImportName) {
const execEnv = this._configOptions.findExecEnvironment(this._executionRootPath);
const moduleDescriptor: ImportedModuleDescriptor = {
leadingDots: 0,
nameParts: this._typeStubTargetImportName.split('.'),
importedSymbols: [],
};
const importResult = this._backgroundAnalysisProgram.importResolver.resolveImport(
'',
execEnv,
moduleDescriptor
);
if (importResult.isImportFound) {
const filesToImport: string[] = [];
// Namespace packages resolve to a directory name, so
// don't include those.
const resolvedPath = importResult.resolvedPaths[importResult.resolvedPaths.length - 1];
// Get the directory that contains the root package.
let targetPath = getDirectoryPath(resolvedPath);
let prevResolvedPath = resolvedPath;
for (let i = importResult.resolvedPaths.length - 2; i >= 0; i--) {
const resolvedPath = importResult.resolvedPaths[i];
if (resolvedPath) {
targetPath = getDirectoryPath(resolvedPath);
prevResolvedPath = resolvedPath;
} else {
// If there was no file corresponding to this portion
// of the name path, assume that it's contained
// within its parent directory.
targetPath = getDirectoryPath(prevResolvedPath);
prevResolvedPath = targetPath;
}
}
if (isDirectory(this._fs, targetPath)) {
this._typeStubTargetPath = targetPath;
}
if (!resolvedPath) {
this._typeStubTargetIsSingleFile = false;
} else {
filesToImport.push(resolvedPath);
this._typeStubTargetIsSingleFile =
importResult.resolvedPaths.length === 1 &&
stripFileExtension(getFileName(importResult.resolvedPaths[0])) !== '__init__';
}
// Add the implicit import paths.
importResult.filteredImplicitImports.forEach((implicitImport) => {
filesToImport.push(implicitImport.path);
});
this._backgroundAnalysisProgram.setAllowedThirdPartyImports([this._typeStubTargetImportName]);
this._backgroundAnalysisProgram.setTrackedFiles(filesToImport);
} else {
this._console.error(`Import '${this._typeStubTargetImportName}' not found`);
}
} else {
let fileList: string[] = [];
this._console.info(`Searching for source files`);
fileList = this._getFileNamesFromFileSpecs();
this._backgroundAnalysisProgram.setTrackedFiles(fileList);
this._backgroundAnalysisProgram.markAllFilesDirty(markFilesDirtyUnconditionally);