-
Notifications
You must be signed in to change notification settings - Fork 189
/
query-history.ts
823 lines (738 loc) · 24.7 KB
/
query-history.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
import * as path from 'path';
import * as vscode from 'vscode';
import { window as Window, env } from 'vscode';
import { CompletedQuery } from './query-results';
import { QueryHistoryConfig } from './config';
import { QueryWithResults } from './run-queries';
import {
showAndLogErrorMessage,
showAndLogInformationMessage,
showAndLogWarningMessage,
showBinaryChoiceDialog
} from './helpers';
import { logger } from './logging';
import { URLSearchParams } from 'url';
import { QueryServerClient } from './queryserver-client';
import { DisposableObject } from './pure/disposable-object';
import { commandRunner } from './commandRunner';
import { assertNever } from './pure/helpers-pure';
/**
* query-history.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 type QueryHistoryItemOptions = {
label?: string; // user-settable label
queryText?: string; // text of the selected file
isQuickQuery?: boolean;
};
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. //
////////////////////////////////////////////////////////////////////////////////////
`;
/**
* Path to icon to display next to a failed query history item.
*/
const FAILED_QUERY_HISTORY_ITEM_ICON = 'media/red-x.svg';
enum SortOrder {
NameAsc = 'NameAsc',
NameDesc = 'NameDesc',
DateAsc = 'DateAsc',
DateDesc = 'DateDesc',
CountAsc = 'CountAsc',
CountDesc = 'CountDesc',
}
/**
* Tree data provider for the query history view.
*/
export class HistoryTreeDataProvider extends DisposableObject {
private _sortOrder = SortOrder.DateAsc;
private _onDidChangeTreeData = super.push(new vscode.EventEmitter<CompletedQuery | undefined>());
readonly onDidChangeTreeData: vscode.Event<CompletedQuery | undefined> = this
._onDidChangeTreeData.event;
private history: CompletedQuery[] = [];
private failedIconPath: string;
/**
* When not undefined, must be reference-equal to an item in `this.databases`.
*/
private current: CompletedQuery | undefined;
constructor(extensionPath: string) {
super();
this.failedIconPath = path.join(
extensionPath,
FAILED_QUERY_HISTORY_ITEM_ICON
);
}
async getTreeItem(element: CompletedQuery): Promise<vscode.TreeItem> {
const treeItem = new vscode.TreeItem(element.toString());
treeItem.command = {
title: 'Query History Item',
command: 'codeQLQueryHistory.itemClicked',
arguments: [element],
};
// Mark this query history item according to whether it has a
// SARIF file so that we can make context menu items conditionally
// available.
const hasResults = await element.query.hasInterpretedResults();
treeItem.contextValue = hasResults
? 'interpretedResultsItem'
: 'rawResultsItem';
if (!element.didRunSuccessfully) {
treeItem.iconPath = this.failedIconPath;
}
return treeItem;
}
getChildren(
element?: CompletedQuery
): vscode.ProviderResult<CompletedQuery[]> {
return element ? [] : this.history.sort((q1, q2) => {
switch (this.sortOrder) {
case SortOrder.NameAsc:
return q1.toString().localeCompare(q2.toString(), env.language);
case SortOrder.NameDesc:
return q2.toString().localeCompare(q1.toString(), env.language);
case SortOrder.DateAsc:
return q1.date.getTime() - q2.date.getTime();
case SortOrder.DateDesc:
return q2.date.getTime() - q1.date.getTime();
case SortOrder.CountAsc:
return q1.resultCount - q2.resultCount;
case SortOrder.CountDesc:
return q2.resultCount - q1.resultCount;
default:
assertNever(this.sortOrder);
}
});
}
getParent(_element: CompletedQuery): vscode.ProviderResult<CompletedQuery> {
return null;
}
getCurrent(): CompletedQuery | undefined {
return this.current;
}
pushQuery(item: CompletedQuery): void {
this.current = item;
this.history.push(item);
this.refresh();
}
setCurrentItem(item: CompletedQuery) {
this.current = item;
}
remove(item: CompletedQuery) {
if (this.current === item) this.current = undefined;
const index = this.history.findIndex((i) => i === item);
if (index >= 0) {
this.history.splice(index, 1);
if (this.current === undefined && this.history.length > 0) {
// Try to keep a current item, near the deleted item if there
// are any available.
this.current = this.history[Math.min(index, this.history.length - 1)];
}
this.refresh();
}
}
get allHistory(): CompletedQuery[] {
return this.history;
}
refresh(completedQuery?: CompletedQuery) {
this._onDidChangeTreeData.fire(completedQuery);
}
find(queryId: number): CompletedQuery | undefined {
return this.allHistory.find((query) => query.query.queryID === queryId);
}
public get sortOrder() {
return this._sortOrder;
}
public set sortOrder(newSortOrder: SortOrder) {
this._sortOrder = newSortOrder;
this._onDidChangeTreeData.fire(undefined);
}
}
/**
* Number of milliseconds two clicks have to arrive apart to be
* considered a double-click.
*/
const DOUBLE_CLICK_TIME = 500;
const NO_QUERY_SELECTED = 'No query selected. Select a query history item you have already run and try again.';
export class QueryHistoryManager extends DisposableObject {
treeDataProvider: HistoryTreeDataProvider;
treeView: vscode.TreeView<CompletedQuery>;
lastItemClick: { time: Date; item: CompletedQuery } | undefined;
compareWithItem: CompletedQuery | undefined;
constructor(
private qs: QueryServerClient,
extensionPath: string,
private queryHistoryConfigListener: QueryHistoryConfig,
private selectedCallback: (item: CompletedQuery) => Promise<void>,
private doCompareCallback: (
from: CompletedQuery,
to: CompletedQuery
) => Promise<void>
) {
super();
const treeDataProvider = (this.treeDataProvider = new HistoryTreeDataProvider(
extensionPath
));
this.treeView = Window.createTreeView('codeQLQueryHistory', {
treeDataProvider,
canSelectMany: true,
});
this.push(this.treeView);
this.push(treeDataProvider);
// 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()
)
);
// Don't allow the selection to become empty
this.push(
this.treeView.onDidChangeSelection(async (ev) => {
if (ev.selection.length == 0) {
this.updateTreeViewSelectionIfVisible();
}
this.updateCompareWith(ev.selection);
})
);
void logger.log('Registering query history panel commands.');
this.push(
commandRunner(
'codeQLQueryHistory.openQuery',
this.handleOpenQuery.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.removeHistoryItem',
this.handleRemoveHistoryItem.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.sortByName',
this.handleSortByName.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.sortByDate',
this.handleSortByDate.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.sortByCount',
this.handleSortByCount.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.setLabel',
this.handleSetLabel.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.compareWith',
this.handleCompareWith.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.showQueryLog',
this.handleShowQueryLog.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.showQueryText',
this.handleShowQueryText.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.viewCsvResults',
this.handleViewCsvResults.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.viewCsvAlerts',
this.handleViewCsvAlerts.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.viewSarifAlerts',
this.handleViewSarifAlerts.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.viewDil',
this.handleViewDil.bind(this)
)
);
this.push(
commandRunner(
'codeQLQueryHistory.itemClicked',
async (item: CompletedQuery) => {
return this.handleItemClicked(item, [item]);
}
)
);
queryHistoryConfigListener.onDidChangeConfiguration(() => {
this.treeDataProvider.refresh();
});
// displays query text in a read-only document
vscode.workspace.registerTextDocumentContentProvider('codeql', {
provideTextDocumentContent(
uri: vscode.Uri
): vscode.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')
);
},
});
}
async invokeCallbackOn(queryHistoryItem: CompletedQuery) {
if (this.selectedCallback !== undefined) {
const sc = this.selectedCallback;
await sc(queryHistoryItem);
}
}
async handleOpenQuery(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
): Promise<void> {
const { finalSingleItem, finalMultiSelect } = this.determineSelection(singleItem, multiSelect);
if (!this.assertSingleQuery(finalMultiSelect)) {
return;
}
if (!finalSingleItem) {
throw new Error(NO_QUERY_SELECTED);
}
const textDocument = await vscode.workspace.openTextDocument(
vscode.Uri.file(finalSingleItem.query.program.queryPath)
);
const editor = await vscode.window.showTextDocument(
textDocument,
vscode.ViewColumn.One
);
const queryText = finalSingleItem.options.queryText;
if (queryText !== undefined && finalSingleItem.options.isQuickQuery) {
await editor.edit((edit) =>
edit.replace(
textDocument.validateRange(
new vscode.Range(0, 0, textDocument.lineCount, 0)
),
queryText
)
);
}
}
async handleRemoveHistoryItem(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
) {
const { finalSingleItem, finalMultiSelect } = this.determineSelection(singleItem, multiSelect);
(finalMultiSelect || [finalSingleItem]).forEach((item) => {
this.treeDataProvider.remove(item);
item.dispose();
});
const current = this.treeDataProvider.getCurrent();
if (current !== undefined) {
await this.treeView.reveal(current);
await this.invokeCallbackOn(current);
}
}
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 handleSetLabel(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
): Promise<void> {
if (!this.assertSingleQuery(multiSelect)) {
return;
}
const response = await vscode.window.showInputBox({
prompt: 'Label:',
placeHolder: '(use default)',
value: singleItem.getLabel(),
});
// 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'
singleItem.options.label = response === '' ? undefined : response;
if (this.treeDataProvider.sortOrder === SortOrder.NameAsc ||
this.treeDataProvider.sortOrder === SortOrder.NameDesc) {
this.treeDataProvider.refresh();
} else {
this.treeDataProvider.refresh(singleItem);
}
}
}
async handleCompareWith(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
) {
try {
if (!singleItem.didRunSuccessfully) {
throw new Error('Please select a successful query.');
}
const from = this.compareWithItem || singleItem;
const to = await this.findOtherQueryToCompare(from, multiSelect);
if (from && to) {
await this.doCompareCallback(from, to);
}
} catch (e) {
void showAndLogErrorMessage(e.message);
}
}
async handleItemClicked(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
) {
const { finalSingleItem, finalMultiSelect } = this.determineSelection(singleItem, multiSelect);
if (!this.assertSingleQuery(finalMultiSelect)) {
return;
}
if (!finalSingleItem) {
throw new Error(NO_QUERY_SELECTED);
}
this.treeDataProvider.setCurrentItem(finalSingleItem);
const now = new Date();
const prevItemClick = this.lastItemClick;
this.lastItemClick = { time: now, item: finalSingleItem };
if (
prevItemClick !== undefined &&
now.valueOf() - prevItemClick.time.valueOf() < DOUBLE_CLICK_TIME &&
finalSingleItem == prevItemClick.item
) {
// show original query file on double click
await this.handleOpenQuery(finalSingleItem, [finalSingleItem]);
} else {
// show results on single click
await this.invokeCallbackOn(finalSingleItem);
}
}
async handleShowQueryLog(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
) {
if (!this.assertSingleQuery(multiSelect)) {
return;
}
if (singleItem.logFileLocation) {
await this.tryOpenExternalFile(singleItem.logFileLocation);
} else {
void showAndLogWarningMessage('No log file available');
}
}
async handleShowQueryText(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
) {
if (!this.assertSingleQuery(multiSelect)) {
return;
}
if (!singleItem) {
throw new Error(NO_QUERY_SELECTED);
}
const queryName = singleItem.queryName.endsWith('.ql')
? singleItem.queryName
: singleItem.queryName + '.ql';
const params = new URLSearchParams({
isQuickEval: String(!!singleItem.query.quickEvalPosition),
queryText: encodeURIComponent(await this.getQueryText(singleItem)),
});
const uri = vscode.Uri.parse(
`codeql:${singleItem.query.queryID}-${queryName}?${params.toString()}`, true
);
const doc = await vscode.workspace.openTextDocument(uri);
await vscode.window.showTextDocument(doc, { preview: false });
}
async handleViewSarifAlerts(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
) {
if (!this.assertSingleQuery(multiSelect)) {
return;
}
const hasInterpretedResults = await singleItem.query.canHaveInterpretedResults();
if (hasInterpretedResults) {
await this.tryOpenExternalFile(
singleItem.query.resultsPaths.interpretedResultsPath
);
} else {
const label = singleItem.getLabel();
void showAndLogInformationMessage(
`Query ${label} has no interpreted results.`
);
}
}
async handleViewCsvResults(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
) {
if (!this.assertSingleQuery(multiSelect)) {
return;
}
if (await singleItem.query.hasCsv()) {
void this.tryOpenExternalFile(singleItem.query.csvPath);
return;
}
await singleItem.query.exportCsvResults(this.qs, singleItem.query.csvPath, () => {
void this.tryOpenExternalFile(
singleItem.query.csvPath
);
});
}
async handleViewCsvAlerts(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
) {
if (!this.assertSingleQuery(multiSelect)) {
return;
}
await this.tryOpenExternalFile(
await singleItem.query.ensureCsvProduced(this.qs)
);
}
async handleViewDil(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[],
) {
if (!this.assertSingleQuery(multiSelect)) {
return;
}
await this.tryOpenExternalFile(
await singleItem.query.ensureDilPath(this.qs)
);
}
async getQueryText(queryHistoryItem: CompletedQuery): Promise<string> {
if (queryHistoryItem.options.queryText) {
return queryHistoryItem.options.queryText;
} else if (queryHistoryItem.query.quickEvalPosition) {
// capture all selected lines
const startLine = queryHistoryItem.query.quickEvalPosition.line;
const endLine = queryHistoryItem.query.quickEvalPosition.endLine;
const textDocument = await vscode.workspace.openTextDocument(
queryHistoryItem.query.quickEvalPosition.fileName
);
return textDocument.getText(
new vscode.Range(startLine - 1, 0, endLine, 0)
);
} else {
return '';
}
}
buildCompletedQuery(info: QueryWithResults): CompletedQuery {
const item = new CompletedQuery(info, this.queryHistoryConfigListener);
return item;
}
addCompletedQuery(item: CompletedQuery) {
this.treeDataProvider.pushQuery(item);
this.updateTreeViewSelectionIfVisible();
}
find(queryId: number): CompletedQuery | undefined {
return this.treeDataProvider.find(queryId);
}
/**
* 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) {
// We must fire the onDidChangeTreeData event to ensure the current element can be selected
// using `reveal` if the tree view was not visible when the current element was added.
this.treeDataProvider.refresh();
void this.treeView.reveal(current);
}
}
}
private async tryOpenExternalFile(fileLocation: string) {
const uri = vscode.Uri.file(fileLocation);
try {
await vscode.window.showTextDocument(uri, { preview: false });
} catch (e) {
if (
e.message.includes(
'Files above 50MB cannot be synchronized with extensions'
) ||
e.message.includes('too large to open')
) {
const res = await showBinaryChoiceDialog(
`VS Code does not allow extensions to open files >50MB. This file
exceeds that limit. Do you want to open it outside of VS Code?
You can also try manually opening it inside VS Code by selecting
the file in the file explorer and dragging it into the workspace.`
);
if (res) {
try {
await vscode.commands.executeCommand('revealFileInOS', uri);
} catch (e) {
void showAndLogErrorMessage(e.message);
}
}
} else {
void showAndLogErrorMessage(`Could not open file ${fileLocation}`);
void logger.log(e.message);
void logger.log(e.stack);
}
}
}
private async findOtherQueryToCompare(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
): Promise<CompletedQuery | undefined> {
const dbName = singleItem.database.name;
// if exactly 2 queries are selected, use those
if (multiSelect?.length === 2) {
// return the query that is not the first selected one
const otherQuery =
singleItem === multiSelect[0] ? multiSelect[1] : multiSelect[0];
if (!otherQuery.didRunSuccessfully) {
throw new Error('Please select a successful query.');
}
if (otherQuery.database.name !== dbName) {
throw new Error('Query databases must be the same.');
}
return otherQuery;
}
if (multiSelect?.length > 1) {
throw new Error('Please select no more than 2 queries.');
}
// otherwise, let the user choose
const comparableQueryLabels = this.treeDataProvider.allHistory
.filter(
(otherQuery) =>
otherQuery !== singleItem &&
otherQuery.didRunSuccessfully &&
otherQuery.database.name === dbName
)
.map((otherQuery) => ({
label: otherQuery.toString(),
description: otherQuery.databaseName,
detail: otherQuery.statusString,
query: otherQuery,
}));
if (comparableQueryLabels.length < 1) {
throw new Error('No other queries available to compare with.');
}
const choice = await vscode.window.showQuickPick(comparableQueryLabels);
return choice?.query;
}
private assertSingleQuery(multiSelect: CompletedQuery[] = [], message = 'Please select a single query.') {
if (multiSelect.length > 1) {
void showAndLogErrorMessage(
message
);
return false;
}
return true;
}
/**
* Updates the compare with source query. This ensures that all compare command invocations
* when exactly 2 queries are selected always have the proper _from_ query. Always use
* compareWithItem as the _from_ query.
*
* The heuristic is this:
*
* 1. If selection is empty or has length > 2 delete compareWithItem.
* 2. If selection is length 1, then set that item to compareWithItem.
* 3. If selection is length 2, then make sure compareWithItem is one of the selected items
* if not, then delete compareWithItem. If it is then, do nothing.
*
* This ensures that compareWithItem is always the first item selected if there are only
* two selected items.
*
* @param newSelection the new selection after the most recent selection change
*/
private updateCompareWith(newSelection: CompletedQuery[]) {
if (newSelection.length === 1) {
this.compareWithItem = newSelection[0];
} else if (
newSelection.length !== 2 ||
!this.compareWithItem ||
!newSelection.includes(this.compareWithItem)
) {
this.compareWithItem = undefined;
}
}
/**
* If no items are selected, attempt to grab the selection from the treeview.
* We need to use this method because when clicking on commands from the view title
* bar, the selections are not passed in.
*
* @param singleItem the single item selected, or undefined if no item is selected
* @param multiSelect a multi-select or undefined if no items are selected
*/
private determineSelection(
singleItem: CompletedQuery,
multiSelect: CompletedQuery[]
): { finalSingleItem: CompletedQuery; finalMultiSelect: CompletedQuery[] } {
if (singleItem === undefined && (multiSelect === undefined || multiSelect.length === 0 || multiSelect[0] === undefined)) {
const selection = this.treeView.selection;
if (selection) {
return {
finalSingleItem: selection[0],
finalMultiSelect: selection
};
}
}
return {
finalSingleItem: singleItem,
finalMultiSelect: multiSelect
};
}
async refreshTreeView(completedQuery: CompletedQuery): Promise<void> {
this.treeDataProvider.refresh(completedQuery);
}
}