-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathquery-history-manager.ts
1115 lines (1003 loc) · 35.7 KB
/
query-history-manager.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 { join, dirname } from "path";
import {
Disposable,
env,
EventEmitter,
ExtensionContext,
ProviderResult,
Range,
TreeView,
Uri,
ViewColumn,
window,
workspace,
} from "vscode";
import { QueryHistoryConfig } from "../config";
import {
showBinaryChoiceDialog,
showInformationMessageWithAction,
} from "../common/vscode/dialog";
import { URLSearchParams } from "url";
import { DisposableObject } from "../common/disposable-object";
import { ONE_HOUR_IN_MS, TWO_HOURS_IN_MS } from "../common/time";
import { assertNever, getErrorMessage } from "../common/helpers-pure";
import { CompletedLocalQueryInfo, LocalQueryInfo } from "../query-results";
import {
getActionsWorkflowRunUrl,
getQueryId,
getQueryText,
QueryHistoryInfo,
} from "./query-history-info";
import { DatabaseManager } from "../databases/local-databases";
import { registerQueryHistoryScrubber } from "./query-history-scrubber";
import {
QueryStatus,
variantAnalysisStatusToQueryStatus,
} from "./query-status";
import { readQueryHistoryFromFile, writeQueryHistoryToFile } from "./store";
import { pathExists } from "fs-extra";
import { HistoryItemLabelProvider } from "./history-item-label-provider";
import { ResultsView, WebviewReveal } from "../local-queries";
import { EvalLogTreeBuilder, EvalLogViewer } from "../query-evaluation-logging";
import {
EvalLogData,
parseViewerData,
} from "../log-insights/log-summary-parser";
import { QueryWithResults } from "../run-queries-shared";
import { QueryRunner } from "../query-server";
import { VariantAnalysisManager } from "../variant-analysis/variant-analysis-manager";
import { VariantAnalysisHistoryItem } from "./variant-analysis-history-item";
import { getTotalResultCount } from "../variant-analysis/shared/variant-analysis";
import { HistoryTreeDataProvider } from "./history-tree-data-provider";
import { QueryHistoryDirs } from "./query-history-dirs";
import { QueryHistoryCommands } from "../common/commands";
import { App } from "../common/app";
import { tryOpenExternalFile } from "../common/vscode/external-files";
import {
createMultiSelectionCommand,
createSingleSelectionCommand,
} from "../common/vscode/selection-commands";
import {
showAndLogErrorMessage,
showAndLogInformationMessage,
showAndLogWarningMessage,
} from "../common/logging";
import { LanguageContextStore } from "../language-context-store";
/**
* query-history-manager.ts
* ------------
* Managing state of previous queries that we've executed.
*
* The source of truth of the current state resides inside the
* `TreeDataProvider` subclass below.
*/
export const SHOW_QUERY_TEXT_MSG = `\
////////////////////////////////////////////////////////////////////////////////////
// This is the text of the entire query file when it was executed for this query //
// run. The text or dependent libraries may have changed since then. //
// //
// This buffer is readonly. To re-execute this query, you must open the original //
// query file. //
////////////////////////////////////////////////////////////////////////////////////
`;
const SHOW_QUERY_TEXT_QUICK_EVAL_MSG = `\
////////////////////////////////////////////////////////////////////////////////////
// This is the Quick Eval selection of the query file when it was executed for //
// this query run. The text or dependent libraries may have changed since then. //
// //
// This buffer is readonly. To re-execute this query, you must open the original //
// query file. //
////////////////////////////////////////////////////////////////////////////////////
`;
enum SortOrder {
NameAsc = "NameAsc",
NameDesc = "NameDesc",
DateAsc = "DateAsc",
DateDesc = "DateDesc",
CountAsc = "CountAsc",
CountDesc = "CountDesc",
}
/**
* Number of milliseconds two clicks have to arrive apart to be
* considered a double-click.
*/
const DOUBLE_CLICK_TIME = 500;
const WORKSPACE_QUERY_HISTORY_FILE = "workspace-query-history.json";
export class QueryHistoryManager extends DisposableObject {
treeDataProvider: HistoryTreeDataProvider;
treeView: TreeView<QueryHistoryInfo>;
lastItemClick: { time: Date; item: QueryHistoryInfo } | undefined;
compareWithItem: LocalQueryInfo | undefined;
queryHistoryScrubber: Disposable | undefined;
private queryMetadataStorageLocation;
private readonly _onDidChangeCurrentQueryItem = super.push(
new EventEmitter<QueryHistoryInfo | undefined>(),
);
readonly onDidChangeCurrentQueryItem =
this._onDidChangeCurrentQueryItem.event;
private readonly _onDidCompleteQuery = super.push(
new EventEmitter<LocalQueryInfo>(),
);
readonly onDidCompleteQuery = this._onDidCompleteQuery.event;
constructor(
private readonly app: App,
private readonly qs: QueryRunner,
private readonly dbm: DatabaseManager,
private readonly localQueriesResultsView: ResultsView,
private readonly variantAnalysisManager: VariantAnalysisManager,
private readonly evalLogViewer: EvalLogViewer,
private readonly queryHistoryDirs: QueryHistoryDirs,
ctx: ExtensionContext,
private readonly queryHistoryConfigListener: QueryHistoryConfig,
private readonly labelProvider: HistoryItemLabelProvider,
private readonly languageContext: LanguageContextStore,
private readonly doCompareCallback: (
from: CompletedLocalQueryInfo,
to: CompletedLocalQueryInfo,
) => Promise<void>,
) {
super();
// Note that we use workspace storage to hold the metadata for the query history.
// This is because the query history is specific to each workspace.
// For situations where `ctx.storageUri` is undefined (i.e., there is no workspace),
// we default to global storage.
this.queryMetadataStorageLocation = join(
(ctx.storageUri || ctx.globalStorageUri).fsPath,
WORKSPACE_QUERY_HISTORY_FILE,
);
this.treeDataProvider = this.push(
new HistoryTreeDataProvider(this.labelProvider, this.languageContext),
);
this.treeView = this.push(
window.createTreeView("codeQLQueryHistory", {
treeDataProvider: this.treeDataProvider,
canSelectMany: true,
}),
);
// Forward any change of current history item from the tree data.
this.push(
this.treeDataProvider.onDidChangeCurrentQueryItem((item) => {
this._onDidChangeCurrentQueryItem.fire(item);
}),
);
// Lazily update the tree view selection due to limitations of TreeView API (see
// `updateTreeViewSelectionIfVisible` doc for details)
this.push(
this.treeView.onDidChangeVisibility(async (_ev) =>
this.updateTreeViewSelectionIfVisible(),
),
);
this.push(
this.treeView.onDidChangeSelection(async (ev) => {
if (ev.selection.length === 0) {
// Don't allow the selection to become empty
this.updateTreeViewSelectionIfVisible();
} else {
this.treeDataProvider.setCurrentItem(ev.selection[0]);
}
if (ev.selection.some((item) => item.t !== "local")) {
// Don't allow comparison of non-local items
this.updateCompareWith([]);
} else {
this.updateCompareWith([...ev.selection] as LocalQueryInfo[]);
}
}),
);
// There are two configuration items that affect the query history:
// 1. The ttl for query history items.
// 2. The default label for query history items.
// When either of these change, must refresh the tree view.
this.push(
queryHistoryConfigListener.onDidChangeConfiguration(() => {
this.treeDataProvider.refresh();
this.registerQueryHistoryScrubber(
queryHistoryConfigListener,
this,
ctx,
);
}),
);
// displays query text in a read-only document
this.push(
workspace.registerTextDocumentContentProvider("codeql", {
provideTextDocumentContent(uri: Uri): ProviderResult<string> {
const params = new URLSearchParams(uri.query);
return (
(JSON.parse(params.get("isQuickEval") || "")
? SHOW_QUERY_TEXT_QUICK_EVAL_MSG
: SHOW_QUERY_TEXT_MSG) + params.get("queryText")
);
},
}),
);
this.registerQueryHistoryScrubber(queryHistoryConfigListener, this, ctx);
this.registerToVariantAnalysisEvents();
this.push(
this.languageContext.onLanguageContextChanged(async () => {
this.treeDataProvider.refresh();
}),
);
}
public getCommands(): QueryHistoryCommands {
return {
"codeQLQueryHistory.sortByName": this.handleSortByName.bind(this),
"codeQLQueryHistory.sortByDate": this.handleSortByDate.bind(this),
"codeQLQueryHistory.sortByCount": this.handleSortByCount.bind(this),
"codeQLQueryHistory.openQueryContextMenu": createSingleSelectionCommand(
this.app.logger,
this.handleOpenQuery.bind(this),
"query",
),
"codeQLQueryHistory.removeHistoryItemContextMenu":
createMultiSelectionCommand(this.handleRemoveHistoryItem.bind(this)),
"codeQLQueryHistory.removeHistoryItemContextInline":
createMultiSelectionCommand(this.handleRemoveHistoryItem.bind(this)),
"codeQLQueryHistory.renameItem": createSingleSelectionCommand(
this.app.logger,
this.handleRenameItem.bind(this),
"query",
),
"codeQLQueryHistory.compareWith": this.handleCompareWith.bind(this),
"codeQLQueryHistory.showEvalLog": createSingleSelectionCommand(
this.app.logger,
this.handleShowEvalLog.bind(this),
"query",
),
"codeQLQueryHistory.showEvalLogSummary": createSingleSelectionCommand(
this.app.logger,
this.handleShowEvalLogSummary.bind(this),
"query",
),
"codeQLQueryHistory.showEvalLogViewer": createSingleSelectionCommand(
this.app.logger,
this.handleShowEvalLogViewer.bind(this),
"query",
),
"codeQLQueryHistory.showQueryLog": createSingleSelectionCommand(
this.app.logger,
this.handleShowQueryLog.bind(this),
"query",
),
"codeQLQueryHistory.showQueryText": createSingleSelectionCommand(
this.app.logger,
this.handleShowQueryText.bind(this),
"query",
),
"codeQLQueryHistory.openQueryDirectory": createSingleSelectionCommand(
this.app.logger,
this.handleOpenQueryDirectory.bind(this),
"query",
),
"codeQLQueryHistory.cancel": createMultiSelectionCommand(
this.handleCancel.bind(this),
),
"codeQLQueryHistory.exportResults": createSingleSelectionCommand(
this.app.logger,
this.handleExportResults.bind(this),
"query",
),
"codeQLQueryHistory.viewCsvResults": createSingleSelectionCommand(
this.app.logger,
this.handleViewCsvResults.bind(this),
"query",
),
"codeQLQueryHistory.viewCsvAlerts": createSingleSelectionCommand(
this.app.logger,
this.handleViewCsvAlerts.bind(this),
"query",
),
"codeQLQueryHistory.viewSarifAlerts": createSingleSelectionCommand(
this.app.logger,
this.handleViewSarifAlerts.bind(this),
"query",
),
"codeQLQueryHistory.viewDil": createSingleSelectionCommand(
this.app.logger,
this.handleViewDil.bind(this),
"query",
),
"codeQLQueryHistory.itemClicked": createSingleSelectionCommand(
this.app.logger,
this.handleItemClicked.bind(this),
"query",
),
"codeQLQueryHistory.openOnGithub": createSingleSelectionCommand(
this.app.logger,
this.handleOpenOnGithub.bind(this),
"query",
),
"codeQLQueryHistory.copyRepoList": createSingleSelectionCommand(
this.app.logger,
this.handleCopyRepoList.bind(this),
"query",
),
"codeQL.exportSelectedVariantAnalysisResults":
this.exportSelectedVariantAnalysisResults.bind(this),
};
}
public completeQuery(info: LocalQueryInfo, results: QueryWithResults): void {
info.completeThisQuery(results);
this._onDidCompleteQuery.fire(info);
}
/**
* Register and create the history scrubber.
*/
private registerQueryHistoryScrubber(
queryHistoryConfigListener: QueryHistoryConfig,
qhm: QueryHistoryManager,
ctx: ExtensionContext,
) {
this.queryHistoryScrubber?.dispose();
// Every hour check if we need to re-run the query history scrubber.
this.queryHistoryScrubber = this.push(
registerQueryHistoryScrubber(
ONE_HOUR_IN_MS,
TWO_HOURS_IN_MS,
queryHistoryConfigListener.ttlInMillis,
this.queryHistoryDirs,
qhm,
ctx,
),
);
}
private registerToVariantAnalysisEvents() {
const variantAnalysisAddedSubscription =
this.variantAnalysisManager.onVariantAnalysisAdded(
async (variantAnalysis) => {
this.addQuery({
t: "variant-analysis",
status: QueryStatus.InProgress,
completed: false,
variantAnalysis,
});
await this.refreshTreeView();
},
);
const variantAnalysisStatusUpdateSubscription =
this.variantAnalysisManager.onVariantAnalysisStatusUpdated(
async (variantAnalysis) => {
const items = this.treeDataProvider.allHistory.filter(
(i) =>
i.t === "variant-analysis" &&
i.variantAnalysis.id === variantAnalysis.id,
);
const status = variantAnalysisStatusToQueryStatus(
variantAnalysis.status,
);
if (items.length > 0) {
items.forEach((item) => {
const variantAnalysisHistoryItem =
item as VariantAnalysisHistoryItem;
variantAnalysisHistoryItem.status = status;
variantAnalysisHistoryItem.failureReason =
variantAnalysis.failureReason;
variantAnalysisHistoryItem.resultCount = getTotalResultCount(
variantAnalysis.scannedRepos,
);
variantAnalysisHistoryItem.variantAnalysis = variantAnalysis;
if (status === QueryStatus.Completed) {
variantAnalysisHistoryItem.completed = true;
}
});
await this.refreshTreeView();
} else {
void this.app.logger.log(
"Variant analysis status update event received for unknown variant analysis",
);
}
},
);
const variantAnalysisRemovedSubscription =
this.variantAnalysisManager.onVariantAnalysisRemoved(
async (variantAnalysis) => {
const items = this.treeDataProvider.allHistory.filter(
(i) =>
i.t === "variant-analysis" &&
i.variantAnalysis.id === variantAnalysis.id,
);
await Promise.all(
items.map(async (item) => {
await this.removeVariantAnalysis(
item as VariantAnalysisHistoryItem,
);
}),
);
},
);
this.push(variantAnalysisAddedSubscription);
this.push(variantAnalysisStatusUpdateSubscription);
this.push(variantAnalysisRemovedSubscription);
}
async readQueryHistory(): Promise<void> {
void this.app.logger.log(
`Reading cached query history from '${this.queryMetadataStorageLocation}'.`,
);
const history = await readQueryHistoryFromFile(
this.queryMetadataStorageLocation,
);
this.treeDataProvider.allHistory = history;
await Promise.all(
this.treeDataProvider.allHistory.map(async (item) => {
if (item.t === "variant-analysis") {
await this.variantAnalysisManager.rehydrateVariantAnalysis(
item.variantAnalysis,
);
}
}),
);
}
async writeQueryHistory(): Promise<void> {
await writeQueryHistoryToFile(
this.treeDataProvider.allHistory,
this.queryMetadataStorageLocation,
);
}
async handleOpenQuery(item: QueryHistoryInfo): Promise<void> {
if (item.t === "variant-analysis") {
await this.variantAnalysisManager.openQueryFile(item.variantAnalysis.id);
return;
}
let queryPath: string;
switch (item.t) {
case "local":
queryPath = item.initialInfo.queryPath;
break;
default:
assertNever(item);
}
const textDocument = await workspace.openTextDocument(Uri.file(queryPath));
const editor = await window.showTextDocument(textDocument, ViewColumn.One);
if (item.t === "local") {
const queryText = item.initialInfo.queryText;
if (queryText !== undefined && item.initialInfo.isQuickQuery) {
await editor.edit((edit) =>
edit.replace(
textDocument.validateRange(
new Range(0, 0, textDocument.lineCount, 0),
),
queryText,
),
);
}
}
}
getCurrentQueryHistoryItem(): QueryHistoryInfo | undefined {
return this.treeDataProvider.getCurrent();
}
async removeDeletedQueries() {
await Promise.all(
this.treeDataProvider.allHistory.map(async (item) => {
if (
item.t === "local" &&
item.completedQuery &&
!(await pathExists(item.completedQuery?.query.querySaveDir))
) {
this.treeDataProvider.remove(item);
}
}),
);
}
async handleRemoveHistoryItem(items: QueryHistoryInfo[]) {
await Promise.all(
items.map(async (item) => {
if (item.t === "local") {
// Removing in progress local queries is not supported. They must be cancelled first.
if (item.status !== QueryStatus.InProgress) {
this.treeDataProvider.remove(item);
// User has explicitly asked for this query to be removed.
// We need to delete it from disk as well.
await item.completedQuery?.query.deleteQuery();
}
} else if (item.t === "variant-analysis") {
await this.removeVariantAnalysis(item);
} else {
assertNever(item);
}
}),
);
await this.writeQueryHistory();
const current = this.treeDataProvider.getCurrent();
if (current !== undefined) {
await this.treeView.reveal(current, { select: true });
await this.openQueryResults(current);
}
}
private async removeVariantAnalysis(
item: VariantAnalysisHistoryItem,
): Promise<void> {
// We can remove a Variant Analysis locally, but not remotely.
// The user must cancel the query on GitHub Actions explicitly.
if (item.status === QueryStatus.InProgress) {
const response = await showBinaryChoiceDialog(
`You are about to delete this query: ${this.labelProvider.getLabel(
item,
)}. Are you sure?`,
);
if (!response) return;
}
this.treeDataProvider.remove(item);
void this.app.logger.log(`Deleted ${this.labelProvider.getLabel(item)}.`);
if (item.status === QueryStatus.InProgress) {
await this.showToastWithWorkflowRunLink(item);
}
await this.variantAnalysisManager.removeVariantAnalysis(
item.variantAnalysis,
);
}
private async showToastWithWorkflowRunLink(
item: VariantAnalysisHistoryItem,
): Promise<void> {
const workflowRunUrl = getActionsWorkflowRunUrl(item);
const message = `Remote query has been removed from history. However, the variant analysis is still running on GitHub Actions. To cancel it, you must go to the [workflow run](${workflowRunUrl}) in your browser.`;
void showInformationMessageWithAction(message, "Go to workflow run").then(
async (shouldOpenWorkflowRun) => {
if (!shouldOpenWorkflowRun) return;
await env.openExternal(Uri.parse(workflowRunUrl));
},
);
}
async handleSortByName() {
if (this.treeDataProvider.sortOrder === SortOrder.NameAsc) {
this.treeDataProvider.sortOrder = SortOrder.NameDesc;
} else {
this.treeDataProvider.sortOrder = SortOrder.NameAsc;
}
}
async handleSortByDate() {
if (this.treeDataProvider.sortOrder === SortOrder.DateAsc) {
this.treeDataProvider.sortOrder = SortOrder.DateDesc;
} else {
this.treeDataProvider.sortOrder = SortOrder.DateAsc;
}
}
async handleSortByCount() {
if (this.treeDataProvider.sortOrder === SortOrder.CountAsc) {
this.treeDataProvider.sortOrder = SortOrder.CountDesc;
} else {
this.treeDataProvider.sortOrder = SortOrder.CountAsc;
}
}
async handleRenameItem(item: QueryHistoryInfo): Promise<void> {
const response = await window.showInputBox({
placeHolder: `(use default: ${this.queryHistoryConfigListener.format})`,
value: item.userSpecifiedLabel ?? "",
title: "Set query label",
prompt:
"Set the query history item label. See the description of the codeQL.queryHistory.format setting for more information.",
});
// undefined response means the user cancelled the dialog; don't change anything
if (response !== undefined) {
// Interpret empty string response as 'go back to using default'
item.userSpecifiedLabel = response === "" ? undefined : response;
await this.refreshTreeView();
}
}
isSuccessfulCompletedLocalQueryInfo(
item: QueryHistoryInfo,
): item is CompletedLocalQueryInfo {
return item.t === "local" && item.completedQuery?.successful === true;
}
async handleCompareWith(
singleItem: QueryHistoryInfo,
multiSelect: QueryHistoryInfo[] | undefined,
) {
multiSelect ||= [singleItem];
if (
!this.isSuccessfulCompletedLocalQueryInfo(singleItem) ||
!multiSelect.every(this.isSuccessfulCompletedLocalQueryInfo)
) {
throw new Error(
"Please only select local queries that have completed successfully.",
);
}
const fromItem = this.getFromQueryToCompare(singleItem, multiSelect);
let toItem: CompletedLocalQueryInfo | undefined = undefined;
try {
toItem = await this.findOtherQueryToCompare(fromItem, multiSelect);
} catch (e) {
void showAndLogErrorMessage(
this.app.logger,
`Failed to compare queries: ${getErrorMessage(e)}`,
);
}
if (toItem !== undefined) {
await this.doCompareCallback(fromItem, toItem);
}
}
async handleItemClicked(item: QueryHistoryInfo) {
this.treeDataProvider.setCurrentItem(item);
const now = new Date();
const prevItemClick = this.lastItemClick;
this.lastItemClick = { time: now, item };
if (
prevItemClick !== undefined &&
now.valueOf() - prevItemClick.time.valueOf() < DOUBLE_CLICK_TIME &&
item === prevItemClick.item
) {
// show original query file on double click
await this.handleOpenQuery(item);
} else if (
item.t === "variant-analysis" ||
item.status === QueryStatus.Completed
) {
// show results on single click (if results view is available)
await this.openQueryResults(item);
}
}
async handleShowQueryLog(item: QueryHistoryInfo) {
// Local queries only
if (item?.t !== "local" || !item.completedQuery) {
return;
}
if (item.completedQuery.logFileLocation) {
await tryOpenExternalFile(
this.app.commands,
item.completedQuery.logFileLocation,
);
} else {
void showAndLogWarningMessage(this.app.logger, "No log file available");
}
}
async handleOpenQueryDirectory(item: QueryHistoryInfo) {
let externalFilePath: string | undefined;
if (item.t === "local") {
const querySaveDir =
item.initialInfo.outputDir?.querySaveDir ??
item.completedQuery?.query.querySaveDir;
if (querySaveDir) {
externalFilePath = join(querySaveDir, "timestamp");
}
} else if (item.t === "variant-analysis") {
externalFilePath = join(
this.variantAnalysisManager.getVariantAnalysisStorageLocation(
item.variantAnalysis.id,
),
"timestamp",
);
} else {
assertNever(item);
}
if (externalFilePath) {
if (!(await pathExists(externalFilePath))) {
// timestamp file is missing (manually deleted?) try selecting the parent folder.
// It's less nice, but at least it will work.
externalFilePath = dirname(externalFilePath);
if (!(await pathExists(externalFilePath))) {
throw new Error(
`Query directory does not exist: ${externalFilePath}`,
);
}
}
try {
await this.app.commands.execute(
"revealFileInOS",
Uri.file(externalFilePath),
);
} catch (e) {
throw new Error(
`Failed to open ${externalFilePath}: ${getErrorMessage(e)}`,
);
}
} else {
this.warnNoQueryDir();
}
}
private warnNoQueryDir() {
void showAndLogWarningMessage(
this.app.logger,
`Results directory is not available for this run.`,
);
}
private warnNoEvalLogs() {
void showAndLogWarningMessage(
this.app.logger,
`Evaluator log, summary, and viewer are not available for this run. Perhaps it failed before evaluation?`,
);
}
private async warnNoEvalLogSummary(item: LocalQueryInfo) {
const evalLogLocation =
item.evalLogLocation ?? item.initialInfo.outputDir?.evalLogPath;
// Summary log file doesn't exist.
if (evalLogLocation && (await pathExists(evalLogLocation))) {
// If raw log does exist, then the summary log is still being generated.
void showAndLogWarningMessage(
this.app.logger,
'The evaluator log summary is still being generated for this run. Please try again later. The summary generation process is tracked in the "CodeQL Extension Log" view.',
);
} else {
this.warnNoEvalLogs();
}
}
async handleShowEvalLog(item: QueryHistoryInfo) {
if (item.t !== "local") {
return;
}
const evalLogLocation =
item.evalLogLocation ?? item.initialInfo.outputDir?.evalLogPath;
if (evalLogLocation && (await pathExists(evalLogLocation))) {
await tryOpenExternalFile(this.app.commands, evalLogLocation);
} else {
this.warnNoEvalLogs();
}
}
async handleShowEvalLogSummary(item: QueryHistoryInfo) {
if (item.t !== "local") {
return;
}
// If the summary file location wasn't saved, display error
if (!item.evalLogSummaryLocation) {
await this.warnNoEvalLogSummary(item);
return;
}
await tryOpenExternalFile(this.app.commands, item.evalLogSummaryLocation);
}
async handleShowEvalLogViewer(item: QueryHistoryInfo) {
if (item.t !== "local") {
return;
}
// If the JSON summary file location wasn't saved, display error
if (item.jsonEvalLogSummaryLocation === undefined) {
await this.warnNoEvalLogSummary(item);
return;
}
// TODO(angelapwen): Stream the file in.
try {
const evalLogData: EvalLogData[] = await parseViewerData(
item.jsonEvalLogSummaryLocation,
);
const evalLogTreeBuilder = new EvalLogTreeBuilder(
item.getQueryName(),
evalLogData,
);
this.evalLogViewer.updateRoots(await evalLogTreeBuilder.getRoots());
} catch (e) {
throw new Error(
`Could not read evaluator log summary JSON file to generate viewer data at ${item.jsonEvalLogSummaryLocation}.`,
);
}
}
async handleCancel(items: QueryHistoryInfo[]) {
const results = items.map(async (item) => {
if (item.status === QueryStatus.InProgress) {
if (item.t === "local") {
item.cancel();
} else if (item.t === "variant-analysis") {
await this.variantAnalysisManager.cancelVariantAnalysis(
item.variantAnalysis.id,
);
} else {
assertNever(item);
}
}
});
await Promise.all(results);
}
async handleShowQueryText(item: QueryHistoryInfo) {
if (item.t === "variant-analysis") {
await this.variantAnalysisManager.openQueryText(item.variantAnalysis.id);
return;
}
const params = new URLSearchParams({
isQuickEval: String(
!!(item.t === "local" && item.initialInfo.quickEvalPosition),
),
queryText: encodeURIComponent(getQueryText(item)),
});
const queryId = getQueryId(item);
const uri = Uri.parse(`codeql:${queryId}.ql?${params.toString()}`, true);
const doc = await workspace.openTextDocument(uri);
await window.showTextDocument(doc, { preview: false });
}
async handleViewSarifAlerts(item: QueryHistoryInfo) {
if (item.t !== "local" || !item.completedQuery) {
return;
}
const query = item.completedQuery.query;
const hasInterpretedResults = query.canHaveInterpretedResults();
if (hasInterpretedResults) {
await tryOpenExternalFile(
this.app.commands,
query.resultsPaths.interpretedResultsPath,
);
} else {
const label = this.labelProvider.getLabel(item);
void showAndLogInformationMessage(
this.app.logger,
`Query ${label} has no interpreted results.`,
);
}
}
async handleViewCsvResults(item: QueryHistoryInfo) {
if (item.t !== "local" || !item.completedQuery) {
return;
}
const query = item.completedQuery.query;
if (await query.hasCsv()) {
void tryOpenExternalFile(this.app.commands, query.csvPath);
return;
}
if (await query.exportCsvResults(this.qs.cliServer, query.csvPath)) {
void tryOpenExternalFile(this.app.commands, query.csvPath);
}
}
async handleViewCsvAlerts(item: QueryHistoryInfo) {
if (item.t !== "local" || !item.completedQuery) {
return;
}
await tryOpenExternalFile(
this.app.commands,
await item.completedQuery.query.ensureCsvAlerts(
this.qs.cliServer,
this.dbm,
),
);
}
async handleViewDil(item: QueryHistoryInfo) {
if (item.t !== "local" || !item.completedQuery) {
return;
}
await tryOpenExternalFile(
this.app.commands,
await item.completedQuery.query.ensureDilPath(this.qs.cliServer),
);
}
async handleOpenOnGithub(item: QueryHistoryInfo) {
if (item.t !== "variant-analysis") {
return;
}
const actionsWorkflowRunUrl = getActionsWorkflowRunUrl(item);
await this.app.commands.execute(
"vscode.open",
Uri.parse(actionsWorkflowRunUrl),
);
}
async handleCopyRepoList(item: QueryHistoryInfo) {
if (item.t !== "variant-analysis") {
return;
}
await this.variantAnalysisManager.copyRepoListToClipboard(
item.variantAnalysis.id,
);
}
async handleExportResults(item: QueryHistoryInfo): Promise<void> {
if (item.t !== "variant-analysis") {
return;
}
await this.variantAnalysisManager.exportResults(item.variantAnalysis.id);
}
/**
* Exports the results of the currently-selected variant analysis.
*/
async exportSelectedVariantAnalysisResults(): Promise<void> {
const queryHistoryItem = this.getCurrentQueryHistoryItem();
if (!queryHistoryItem || queryHistoryItem.t !== "variant-analysis") {
throw new Error(
"No variant analysis results currently open. To open results, click an item in the query history view.",
);
}
await this.variantAnalysisManager.exportResults(
queryHistoryItem.variantAnalysis.id,
);
}
addQuery(item: QueryHistoryInfo) {
this.treeDataProvider.pushQuery(item);
this.updateTreeViewSelectionIfVisible();
}
/**
* Update the tree view selection if the tree view is visible.
*
* If the tree view is not visible, we must wait until it becomes visible before updating the
* selection. This is because the only mechanism for updating the selection of the tree view
* has the side-effect of revealing the tree view. This changes the active sidebar to CodeQL,
* interrupting user workflows such as writing a commit message on the source control sidebar.
*/
private updateTreeViewSelectionIfVisible() {
if (this.treeView.visible) {
const current = this.treeDataProvider.getCurrent();
if (current !== undefined) {