forked from github/vscode-codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension.ts
1371 lines (1236 loc) · 43 KB
/
extension.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
import "source-map-support/register";
import type { CancellationToken, Disposable, ExtensionContext } from "vscode";
import {
env,
extensions,
languages,
ProgressLocation,
Uri,
version as vscodeVersion,
window as Window,
workspace,
} from "vscode";
import type { LanguageClient } from "vscode-languageclient/node";
import { arch, homedir, platform } from "os";
import { ensureDir } from "fs-extra";
import { join } from "path";
import { dirSync } from "tmp-promise";
import { lt, parse } from "semver";
import { watch } from "chokidar";
import {
activate as archiveFilesystemProvider_activate,
zipArchiveScheme,
} from "./common/vscode/archive-filesystem-provider";
import { CliVersionConstraint, CodeQLCliServer } from "./codeql-cli/cli";
import {
ADD_DATABASE_SOURCE_TO_WORKSPACE_SETTING,
addDatabaseSourceToWorkspace,
CliConfigListener,
DistributionConfigListener,
GitHubDatabaseConfigListener,
joinOrderWarningThreshold,
QueryHistoryConfigListener,
QueryServerConfigListener,
VariantAnalysisConfigListener,
} from "./config";
import {
AstViewer,
createLanguageClient,
getQueryEditorCommands,
install,
TemplatePrintAstProvider,
TemplatePrintCfgProvider,
TemplateQueryDefinitionProvider,
TemplateQueryReferenceProvider,
} from "./language-support";
import { DatabaseManager } from "./databases/local-databases";
import { DatabaseUI } from "./databases/local-databases-ui";
import type { FindDistributionResult } from "./codeql-cli/distribution";
import {
DEFAULT_DISTRIBUTION_VERSION_RANGE,
DistributionKind,
DistributionManager,
DistributionUpdateCheckResultKind,
FindDistributionResultKind,
} from "./codeql-cli/distribution";
import {
GithubApiError,
GithubRateLimitedError,
} from "./codeql-cli/distribution/github-api-error";
import { tmpDir, tmpDirDisposal } from "./tmp-dir";
import { prepareCodeTour } from "./code-tour/code-tour";
import {
showBinaryChoiceDialog,
showInformationMessageWithAction,
} from "./common/vscode/dialog";
import {
asError,
assertNever,
getErrorMessage,
getErrorStack,
} from "./common/helpers-pure";
import {
LocalQueries,
QuickEvalCodeLensProvider,
ResultsView,
WebviewReveal,
} from "./local-queries";
import type { BaseLogger } from "./common/logging";
import {
showAndLogErrorMessage,
showAndLogExceptionWithTelemetry,
showAndLogInformationMessage,
showAndLogWarningMessage,
} from "./common/logging";
import type { ProgressReporter } from "./common/logging/vscode";
import {
extLogger,
languageServerLogger,
queryServerLogger,
} from "./common/logging/vscode";
import { QueryHistoryManager } from "./query-history/query-history-manager";
import type { CompletedLocalQueryInfo } from "./query-results";
import { CompareView } from "./compare/compare-view";
import {
initializeTelemetry,
telemetryListener,
} from "./common/vscode/telemetry";
import type { ProgressCallback } from "./common/vscode/progress";
import { withProgress } from "./common/vscode/progress";
import { CodeQlStatusBarHandler } from "./status-bar";
import { getPackagingCommands } from "./packaging";
import { HistoryItemLabelProvider } from "./query-history/history-item-label-provider";
import { EvalLogViewer } from "./query-evaluation-logging";
import { SummaryLanguageSupport } from "./log-insights/summary-language-support";
import { JoinOrderScannerProvider } from "./log-insights/join-order";
import { LogScannerService } from "./log-insights/log-scanner-service";
import { VariantAnalysisView } from "./variant-analysis/variant-analysis-view";
import { VariantAnalysisViewSerializer } from "./variant-analysis/variant-analysis-view-serializer";
import { VariantAnalysisManager } from "./variant-analysis/variant-analysis-manager";
import { createVariantAnalysisContentProvider } from "./variant-analysis/variant-analysis-content-provider";
import { VSCodeMockGitHubApiServer } from "./common/mock-gh-api/vscode/vscode-mock-gh-api-server";
import { VariantAnalysisResultsManager } from "./variant-analysis/variant-analysis-results-manager";
import { ExtensionApp } from "./common/vscode/extension-app";
import { DbModule } from "./databases/db-module";
import { redactableError } from "./common/errors";
import { QLDebugAdapterDescriptorFactory } from "./debugger/debugger-factory";
import type { QueryHistoryDirs } from "./query-history/query-history-dirs";
import type {
AllExtensionCommands,
BaseCommands,
PreActivationCommands,
QueryServerCommands,
} from "./common/commands";
import { getAstCfgCommands } from "./language-support/ast-viewer/ast-cfg-commands";
import type { App } from "./common/app";
import { registerCommandWithErrorHandling } from "./common/vscode/commands";
import { DebuggerUI } from "./debugger/debugger-ui";
import { ModelEditorModule } from "./model-editor/model-editor-module";
import { TestManager } from "./query-testing/test-manager";
import { TestRunner } from "./query-testing/test-runner";
import { QueryRunner, QueryServerClient } from "./query-server";
import { QueriesModule } from "./queries-panel/queries-module";
import { OpenReferencedFileCodeLensProvider } from "./local-queries/open-referenced-file-code-lens-provider";
import { LanguageContextStore } from "./language-context-store";
import { LanguageSelectionPanel } from "./language-selection-panel/language-selection-panel";
import { GitHubDatabasesModule } from "./databases/github-databases";
import { DatabaseFetcher } from "./databases/database-fetcher";
import { ComparePerformanceView } from "./compare-performance/compare-performance-view";
/**
* extension.ts
* ------------
*
* A vscode extension for CodeQL query development.
*/
/**
* Holds when we have proceeded past the initial phase of extension activation in which
* we are trying to ensure that a valid CodeQL distribution exists, and we're actually setting
* up the bulk of the extension.
*/
let beganMainExtensionActivation = false;
/**
* A list of vscode-registered-command disposables that contain
* temporary stub handlers for commands that exist package.json (hence
* are already connected to onscreen ui elements) but which will not
* have any useful effect if we haven't located a CodeQL distribution.
*/
const errorStubs: Disposable[] = [];
/**
* Holds when we are installing or checking for updates to the distribution.
*/
let isInstallingOrUpdatingDistribution = false;
const extensionId = "GitHub.vscode-codeql";
const extension = extensions.getExtension(extensionId);
/**
* Return all commands that are not tied to the more specific managers.
*/
function getCommands(
app: App,
cliServer: CodeQLCliServer,
queryRunner: QueryRunner,
languageClient: LanguageClient,
): BaseCommands {
const getCliVersion = async () => {
try {
return await cliServer.getVersion();
} catch {
return "<missing>";
}
};
const restartQueryServer = async () =>
withProgress(
async (progress: ProgressCallback) => {
// Restart all of the spawned servers: cli, query, and language.
cliServer.restartCliServer();
await Promise.all([
queryRunner.restartQueryServer(progress),
async () => {
if (languageClient.isRunning()) {
await languageClient.restart();
} else {
await languageClient.start();
}
},
]);
void showAndLogInformationMessage(
queryServerLogger,
"CodeQL Query Server restarted.",
);
},
{
title: "Restarting Query Server",
},
);
return {
"codeQL.openDocumentation": async () => {
await env.openExternal(Uri.parse("https://codeql.github.com/docs/"));
},
"codeQL.restartQueryServer": restartQueryServer,
"codeQL.restartQueryServerOnConfigChange": restartQueryServer,
"codeQL.restartLegacyQueryServerOnConfigChange": restartQueryServer,
"codeQL.restartQueryServerOnExternalConfigChange": restartQueryServer,
"codeQL.copyVersion": async () => {
const text = `CodeQL extension version: ${
extension?.packageJSON.version
} \nCodeQL CLI version: ${await getCliVersion()} \nPlatform: ${platform()} ${arch()}`;
await env.clipboard.writeText(text);
void showAndLogInformationMessage(extLogger, text);
},
"codeQL.authenticateToGitHub": async () => {
/**
* Credentials for authenticating to GitHub.
* These are used when making API calls.
*/
const octokit = await app.credentials.getOctokit();
const userInfo = await octokit.users.getAuthenticated();
void showAndLogInformationMessage(
extLogger,
`Authenticated to GitHub as user: ${userInfo.data.login}`,
);
},
"codeQL.showLogs": async () => {
extLogger.show();
},
};
}
/**
* If the user tries to execute vscode commands after extension activation is failed, give
* a sensible error message.
*
* @param excludedCommands List of commands for which we should not register error stubs.
*/
function registerErrorStubs(
excludedCommands: string[],
stubGenerator: (command: string) => () => Promise<void>,
): void {
// Remove existing stubs
errorStubs.forEach((stub) => stub.dispose());
if (extension === undefined) {
throw new Error(`Can't find extension ${extensionId}`);
}
const stubbedCommands: string[] =
extension.packageJSON.contributes.commands.map(
(entry: { command: string }) => entry.command,
);
stubbedCommands.forEach((command) => {
if (excludedCommands.indexOf(command) === -1) {
// This is purposefully using `registerCommandWithErrorHandling` instead of the command manager because these
// commands are untyped and registered pre-activation.
errorStubs.push(
registerCommandWithErrorHandling(command, stubGenerator(command)),
);
}
});
}
/**
* The publicly available interface for this extension. This is to
* be used in our tests.
*/
export interface CodeQLExtensionInterface {
readonly ctx: ExtensionContext;
readonly cliServer: CodeQLCliServer;
readonly qs: QueryRunner;
readonly distributionManager: DistributionManager;
readonly databaseManager: DatabaseManager;
readonly databaseUI: DatabaseUI;
readonly localQueries: LocalQueries;
readonly variantAnalysisManager: VariantAnalysisManager;
readonly dispose: () => void;
}
interface DistributionUpdateConfig {
isUserInitiated: boolean;
shouldDisplayMessageWhenNoUpdates: boolean;
allowAutoUpdating: boolean;
}
const shouldUpdateOnNextActivationKey = "shouldUpdateOnNextActivation";
const codeQlVersionRange = DEFAULT_DISTRIBUTION_VERSION_RANGE;
// This is the minimum version of vscode that we _want_ to support. We want to update to Node 20, but that
// requires 1.90 or later. If we change the minimum version in the package.json, then anyone on an older version of vscode will
// silently be unable to upgrade. So, the solution is to first bump the minimum version here and release. Then
// bump the version in the package.json and release again. This way, anyone on an older version of vscode will get a warning
// before silently being refused to upgrade.
const MIN_VERSION = "1.90.0";
function sendConfigTelemetryData() {
const config: Record<string, string> = {};
config[ADD_DATABASE_SOURCE_TO_WORKSPACE_SETTING.qualifiedName] =
addDatabaseSourceToWorkspace().toString();
telemetryListener?.sendConfigInformation(config);
}
/**
* Returns the CodeQLExtensionInterface, or an empty object if the interface is not
* available after activation is complete. This will happen if there is no cli
* installed when the extension starts. Downloading and installing the cli
* will happen at a later time.
*
* @param ctx The extension context
*
* @returns CodeQLExtensionInterface
*/
// ts-unused-exports:disable-next-line
export async function activate(
ctx: ExtensionContext,
): Promise<CodeQLExtensionInterface | undefined> {
void extLogger.log(`Starting ${extensionId} extension`);
if (extension === undefined) {
throw new Error(`Can't find extension ${extensionId}`);
}
const distributionConfigListener = new DistributionConfigListener();
await initializeLogging(ctx);
const telemetryListener = await initializeTelemetry(extension, ctx);
addUnhandledRejectionListener();
install();
const app = new ExtensionApp(ctx);
sendConfigTelemetryData();
const quickEvalCodeLensProvider = new QuickEvalCodeLensProvider();
languages.registerCodeLensProvider(
{ scheme: "file", language: "ql" },
quickEvalCodeLensProvider,
);
const openReferencedFileCodeLensProvider =
new OpenReferencedFileCodeLensProvider();
languages.registerCodeLensProvider(
{ scheme: "file", pattern: "**/*.qlref" },
openReferencedFileCodeLensProvider,
);
ctx.subscriptions.push(distributionConfigListener);
const distributionManager = new DistributionManager(
distributionConfigListener,
codeQlVersionRange,
ctx,
app.logger,
);
await distributionManager.initialize();
registerErrorStubs([checkForUpdatesCommand], (command) => async () => {
void showAndLogErrorMessage(
extLogger,
`Can't execute ${command}: waiting to finish loading CodeQL CLI.`,
);
});
// Checking the vscode version should not block extension activation.
void assertVSCodeVersionGreaterThan(MIN_VERSION, ctx);
ctx.subscriptions.push(
distributionConfigListener.onDidChangeConfiguration(() =>
installOrUpdateThenTryActivate(
ctx,
app,
distributionManager,
distributionConfigListener,
{
isUserInitiated: true,
shouldDisplayMessageWhenNoUpdates: false,
allowAutoUpdating: true,
},
),
),
);
ctx.subscriptions.push(
// This is purposefully using `registerCommandWithErrorHandling` directly instead of the command manager
// because this command is registered pre-activation.
registerCommandWithErrorHandling(checkForUpdatesCommand, () =>
installOrUpdateThenTryActivate(
ctx,
app,
distributionManager,
distributionConfigListener,
{
isUserInitiated: true,
shouldDisplayMessageWhenNoUpdates: true,
allowAutoUpdating: true,
},
),
),
);
const variantAnalysisViewSerializer = new VariantAnalysisViewSerializer(app);
Window.registerWebviewPanelSerializer(
VariantAnalysisView.viewType,
variantAnalysisViewSerializer,
);
const codeQlExtension = await installOrUpdateThenTryActivate(
ctx,
app,
distributionManager,
distributionConfigListener,
{
isUserInitiated: !!ctx.globalState.get(shouldUpdateOnNextActivationKey),
shouldDisplayMessageWhenNoUpdates: false,
// only auto update on startup if the user has previously requested an update
// otherwise, ask user to accept the update
allowAutoUpdating: !!ctx.globalState.get(shouldUpdateOnNextActivationKey),
},
);
if (codeQlExtension !== undefined) {
variantAnalysisViewSerializer.onExtensionLoaded(
codeQlExtension.variantAnalysisManager,
);
codeQlExtension.cliServer.addVersionChangedListener((ver) => {
telemetryListener.cliVersion = ver?.version;
});
let unsupportedWarningShown = false;
codeQlExtension.cliServer.addVersionChangedListener((ver) => {
if (!ver) {
return;
}
if (unsupportedWarningShown) {
return;
}
if (
CliVersionConstraint.OLDEST_SUPPORTED_CLI_VERSION.compare(
ver.version,
) <= 0
) {
return;
}
void showAndLogWarningMessage(
extLogger,
`You are using an unsupported version of the CodeQL CLI (${ver.version}). ` +
`The minimum supported version is ${CliVersionConstraint.OLDEST_SUPPORTED_CLI_VERSION}. ` +
`Please upgrade to a newer version of the CodeQL CLI.`,
);
unsupportedWarningShown = true;
});
}
return codeQlExtension;
}
async function installOrUpdateDistributionWithProgressTitle(
ctx: ExtensionContext,
app: ExtensionApp,
distributionManager: DistributionManager,
progressTitle: string,
config: DistributionUpdateConfig,
): Promise<void> {
const minSecondsSinceLastUpdateCheck = config.isUserInitiated ? 0 : 86400;
const noUpdatesLoggingFunc = config.shouldDisplayMessageWhenNoUpdates
? showAndLogInformationMessage
: async (logger: BaseLogger, message: string) => void logger.log(message);
const result =
await distributionManager.checkForUpdatesToExtensionManagedDistribution(
minSecondsSinceLastUpdateCheck,
);
// We do want to auto update if there is no distribution at all
const allowAutoUpdating =
config.allowAutoUpdating || !(await distributionManager.hasDistribution());
switch (result.kind) {
case DistributionUpdateCheckResultKind.AlreadyCheckedRecentlyResult:
void extLogger.log(
"Didn't perform CodeQL CLI update check since a check was already performed within the previous " +
`${minSecondsSinceLastUpdateCheck} seconds.`,
);
break;
case DistributionUpdateCheckResultKind.AlreadyUpToDate:
await noUpdatesLoggingFunc(extLogger, "CodeQL CLI already up to date.");
break;
case DistributionUpdateCheckResultKind.InvalidLocation:
await noUpdatesLoggingFunc(
extLogger,
"CodeQL CLI is installed externally so could not be updated.",
);
break;
case DistributionUpdateCheckResultKind.UpdateAvailable:
if (beganMainExtensionActivation || !allowAutoUpdating) {
const updateAvailableMessage =
`Version "${result.updatedRelease.name}" of the CodeQL CLI is now available. ` +
"Do you wish to upgrade?";
await ctx.globalState.update(shouldUpdateOnNextActivationKey, true);
if (
await showInformationMessageWithAction(
updateAvailableMessage,
"Restart and Upgrade",
)
) {
await app.commands.execute("workbench.action.reloadWindow");
}
} else {
await withProgress(
(progress) =>
distributionManager.installExtensionManagedDistributionRelease(
result.updatedRelease,
progress,
),
{
title: progressTitle,
},
);
await ctx.globalState.update(shouldUpdateOnNextActivationKey, false);
void showAndLogInformationMessage(
extLogger,
`CodeQL CLI updated to version "${result.updatedRelease.name}".`,
);
}
break;
default:
assertNever(result);
}
}
async function installOrUpdateDistribution(
ctx: ExtensionContext,
app: ExtensionApp,
distributionManager: DistributionManager,
config: DistributionUpdateConfig,
): Promise<void> {
if (isInstallingOrUpdatingDistribution) {
throw new Error("Already installing or updating CodeQL CLI");
}
isInstallingOrUpdatingDistribution = true;
const codeQlInstalled =
(await distributionManager.getCodeQlPathWithoutVersionCheck()) !==
undefined;
const willUpdateCodeQl = ctx.globalState.get(shouldUpdateOnNextActivationKey);
const messageText = willUpdateCodeQl
? "Updating CodeQL CLI"
: codeQlInstalled
? "Checking for updates to CodeQL CLI"
: "Installing CodeQL CLI";
try {
await installOrUpdateDistributionWithProgressTitle(
ctx,
app,
distributionManager,
messageText,
config,
);
} catch (e) {
// Don't rethrow the exception, because if the config is changed, we want to be able to retry installing
// or updating the distribution.
const alertFunction =
codeQlInstalled && !config.isUserInitiated
? showAndLogWarningMessage
: showAndLogErrorMessage;
const taskDescription = `${
willUpdateCodeQl
? "update"
: codeQlInstalled
? "check for updates to"
: "install"
} CodeQL CLI`;
if (e instanceof GithubRateLimitedError) {
void alertFunction(
extLogger,
`Rate limited while trying to ${taskDescription}. Please try again after ` +
`your rate limit window resets at ${e.rateLimitResetDate.toLocaleString(
env.language,
)}.`,
);
} else if (e instanceof GithubApiError) {
void alertFunction(
extLogger,
`Encountered GitHub API error while trying to ${taskDescription}. ${e}`,
);
}
void alertFunction(extLogger, `Unable to ${taskDescription}. ${e}`);
} finally {
isInstallingOrUpdatingDistribution = false;
}
}
async function getDistributionDisplayingDistributionWarnings(
distributionManager: DistributionManager,
): Promise<FindDistributionResult> {
const result = await distributionManager.getDistribution();
switch (result.kind) {
case FindDistributionResultKind.CompatibleDistribution:
void extLogger.log(
`Found compatible version of CodeQL CLI (version ${result.versionAndFeatures.version.raw})`,
);
break;
case FindDistributionResultKind.IncompatibleDistribution: {
const fixGuidanceMessage = (() => {
switch (result.distribution.kind) {
case DistributionKind.ExtensionManaged:
return 'Please update the CodeQL CLI by running the "CodeQL: Check for CLI Updates" command.';
case DistributionKind.CustomPathConfig:
return `Please update the "CodeQL CLI Executable Path" setting to point to a CLI in the version range ${codeQlVersionRange}.`;
case DistributionKind.PathEnvironmentVariable:
return (
`Please update the CodeQL CLI on your PATH to a version compatible with ${codeQlVersionRange}, or ` +
`set the "CodeQL CLI Executable Path" setting to the path of a CLI version compatible with ${codeQlVersionRange}.`
);
}
})();
void showAndLogWarningMessage(
extLogger,
`The current version of the CodeQL CLI (${result.versionAndFeatures.version.raw}) ` +
`is incompatible with this extension. ${fixGuidanceMessage}`,
);
break;
}
case FindDistributionResultKind.UnknownCompatibilityDistribution:
void showAndLogWarningMessage(
extLogger,
"Compatibility with the configured CodeQL CLI could not be determined. " +
"You may experience problems using the extension.",
);
break;
case FindDistributionResultKind.NoDistribution:
void showAndLogErrorMessage(
extLogger,
"The CodeQL CLI could not be found.",
);
break;
default:
assertNever(result);
}
return result;
}
async function installOrUpdateThenTryActivate(
ctx: ExtensionContext,
app: ExtensionApp,
distributionManager: DistributionManager,
distributionConfigListener: DistributionConfigListener,
config: DistributionUpdateConfig,
): Promise<CodeQLExtensionInterface | undefined> {
await installOrUpdateDistribution(ctx, app, distributionManager, config);
try {
await prepareCodeTour(app.commands);
} catch (e: unknown) {
void extLogger.log(
`Could not open tutorial workspace automatically: ${getErrorMessage(e)}`,
);
}
// Display the warnings even if the extension has already activated.
const distributionResult =
await getDistributionDisplayingDistributionWarnings(distributionManager);
if (
!beganMainExtensionActivation &&
distributionResult.kind !== FindDistributionResultKind.NoDistribution
) {
return await activateWithInstalledDistribution(
ctx,
app,
distributionManager,
distributionConfigListener,
);
}
if (distributionResult.kind === FindDistributionResultKind.NoDistribution) {
registerErrorStubs([checkForUpdatesCommand], (command) => async () => {
void extLogger.log(`Can't execute ${command}: missing CodeQL CLI.`);
const showLogName = "Show Log";
const installActionName = "Install CodeQL CLI";
const chosenAction = await Window.showErrorMessage(
`Can't execute ${command}: missing CodeQL CLI.`,
showLogName,
installActionName,
);
if (chosenAction === showLogName) {
extLogger.show();
} else if (chosenAction === installActionName) {
await installOrUpdateThenTryActivate(
ctx,
app,
distributionManager,
distributionConfigListener,
{
isUserInitiated: true,
shouldDisplayMessageWhenNoUpdates: false,
allowAutoUpdating: true,
},
);
}
});
}
return undefined;
}
const CLEAR_PACK_CACHE_ON_EDIT_GLOBS = [
"**/codeql-pack.yml",
"**/qlpack.yml",
"**/queries.xml",
"**/codeql-pack.lock.yml",
"**/qlpack.lock.yml",
"**/*.dbscheme",
".codeqlmanifest.json",
"codeql-workspace.yml",
];
async function activateWithInstalledDistribution(
ctx: ExtensionContext,
app: ExtensionApp,
distributionManager: DistributionManager,
distributionConfigListener: DistributionConfigListener,
): Promise<CodeQLExtensionInterface> {
beganMainExtensionActivation = true;
// Remove any error stubs command handlers left over from first part
// of activation.
errorStubs.forEach((stub) => stub.dispose());
void extLogger.log("Initializing configuration listener...");
const qlConfigurationListener =
await QueryServerConfigListener.createQueryServerConfigListener(
distributionManager,
);
ctx.subscriptions.push(qlConfigurationListener);
void extLogger.log("Initializing CodeQL cli server...");
const cliServer = new CodeQLCliServer(
app,
distributionManager,
new CliConfigListener(),
extLogger,
);
ctx.subscriptions.push(cliServer);
watchExternalConfigFile(app, ctx);
const statusBar = new CodeQlStatusBarHandler(
cliServer,
distributionConfigListener,
);
ctx.subscriptions.push(statusBar);
void extLogger.log("Initializing query server client.");
const qs = await createQueryServer(
app,
qlConfigurationListener,
cliServer,
ctx,
);
for (const glob of CLEAR_PACK_CACHE_ON_EDIT_GLOBS) {
const fsWatcher = workspace.createFileSystemWatcher(glob);
ctx.subscriptions.push(fsWatcher);
const clearPackCache = async (_uri: Uri) => {
await qs.clearPackCache();
};
fsWatcher.onDidCreate(clearPackCache);
fsWatcher.onDidChange(clearPackCache);
fsWatcher.onDidDelete(clearPackCache);
}
void extLogger.log("Initializing language context.");
const languageContext = new LanguageContextStore(app);
void extLogger.log("Initializing language selector.");
const languageSelectionPanel = new LanguageSelectionPanel(languageContext);
ctx.subscriptions.push(languageSelectionPanel);
void extLogger.log("Initializing database manager.");
const dbm = new DatabaseManager(
ctx,
app,
qs,
cliServer,
languageContext,
extLogger,
);
// Let this run async.
void dbm.loadPersistedState();
const databaseFetcher = new DatabaseFetcher(
app,
dbm,
getContextStoragePath(ctx),
cliServer,
);
ctx.subscriptions.push(dbm);
void extLogger.log("Initializing database panel.");
const databaseUI = new DatabaseUI(
app,
dbm,
databaseFetcher,
languageContext,
qs,
getContextStoragePath(ctx),
ctx.extensionPath,
);
ctx.subscriptions.push(databaseUI);
const queriesModule = QueriesModule.initialize(app, languageContext);
void extLogger.log("Initializing evaluator log viewer.");
const evalLogViewer = new EvalLogViewer();
ctx.subscriptions.push(evalLogViewer);
void extLogger.log("Initializing query history manager.");
const queryHistoryConfigurationListener = new QueryHistoryConfigListener();
ctx.subscriptions.push(queryHistoryConfigurationListener);
const queryStorageDir = join(ctx.globalStorageUri.fsPath, "queries");
await ensureDir(queryStorageDir);
// Store contextual queries in a temporary folder so that they are removed
// when the application closes. There is no need for the user to interact with them.
const contextualQueryStorageDir = join(
tmpDir.name,
"contextual-query-storage",
);
await ensureDir(contextualQueryStorageDir);
const labelProvider = new HistoryItemLabelProvider(
queryHistoryConfigurationListener,
);
void extLogger.log("Initializing results panel interface.");
const localQueryResultsView = new ResultsView(
app,
dbm,
cliServer,
queryServerLogger,
labelProvider,
);
ctx.subscriptions.push(localQueryResultsView);
void extLogger.log("Initializing variant analysis manager.");
const dbModule = await DbModule.initialize(app);
const variantAnalysisStorageDir = join(
ctx.globalStorageUri.fsPath,
"variant-analyses",
);
await ensureDir(variantAnalysisStorageDir);
const variantAnalysisConfig = new VariantAnalysisConfigListener();
const variantAnalysisResultsManager = new VariantAnalysisResultsManager(
cliServer,
variantAnalysisConfig,
extLogger,
);
const variantAnalysisManager = new VariantAnalysisManager(
app,
cliServer,
variantAnalysisStorageDir,
variantAnalysisResultsManager,
dbModule.dbManager,
variantAnalysisConfig,
);
ctx.subscriptions.push(variantAnalysisManager);
ctx.subscriptions.push(variantAnalysisResultsManager);
ctx.subscriptions.push(
workspace.registerTextDocumentContentProvider(
"codeql-variant-analysis",
createVariantAnalysisContentProvider(variantAnalysisManager),
),
);
const githubDatabaseConfigListener = new GitHubDatabaseConfigListener();
await GitHubDatabasesModule.initialize(
app,
dbm,
databaseFetcher,
githubDatabaseConfigListener,
);
void extLogger.log("Initializing query history.");
const queryHistoryDirs: QueryHistoryDirs = {
localQueriesDirPath: queryStorageDir,
variantAnalysesDirPath: variantAnalysisStorageDir,
};
const qhm = new QueryHistoryManager(
app,
qs,
dbm,
localQueryResultsView,
variantAnalysisManager,
evalLogViewer,
queryHistoryDirs,
ctx,
queryHistoryConfigurationListener,
labelProvider,
languageContext,
async (
from: CompletedLocalQueryInfo,
to: CompletedLocalQueryInfo,
): Promise<void> => showResultsForComparison(compareView, from, to),
async (
from: CompletedLocalQueryInfo,
to: CompletedLocalQueryInfo | undefined,
): Promise<void> =>
showPerformanceComparison(comparePerformanceView, from, to),
);
ctx.subscriptions.push(qhm);
void extLogger.log("Initializing evaluation log scanners.");
const logScannerService = new LogScannerService(qhm);
ctx.subscriptions.push(logScannerService);
ctx.subscriptions.push(
logScannerService.scanners.registerLogScannerProvider(
new JoinOrderScannerProvider(() => joinOrderWarningThreshold()),
),
);
void extLogger.log("Initializing compare view.");
const compareView = new CompareView(
app,
dbm,
cliServer,
queryServerLogger,
labelProvider,
async (item: CompletedLocalQueryInfo) =>
localQueries.showResultsForCompletedQuery(item, WebviewReveal.Forced),
);
ctx.subscriptions.push(compareView);
void extLogger.log("Initializing performance comparison view.");
const comparePerformanceView = new ComparePerformanceView(
app,
queryServerLogger,
labelProvider,
localQueryResultsView,
);
ctx.subscriptions.push(comparePerformanceView);
void extLogger.log("Initializing source archive filesystem provider.");
archiveFilesystemProvider_activate(ctx, dbm);
const qhelpTmpDir = dirSync({
prefix: "qhelp_",
keep: false,
unsafeCleanup: true,
});
ctx.subscriptions.push({ dispose: qhelpTmpDir.removeCallback });
ctx.subscriptions.push(tmpDirDisposal);
void extLogger.log("Initializing CodeQL language server.");
const languageClient = createLanguageClient(qlConfigurationListener);
const localQueries = new LocalQueries(
app,
qs,
qhm,
dbm,
databaseFetcher,
cliServer,
databaseUI,
localQueryResultsView,
queryStorageDir,
languageContext,
);
ctx.subscriptions.push(localQueries);
queriesModule.onDidChangeSelection((event) =>
localQueries.setSelectedQueryTreeViewItems(event.selection),
);
void extLogger.log("Initializing debugger factory.");