-
Notifications
You must be signed in to change notification settings - Fork 228
Expand file tree
/
Copy pathlocal-databases-ui.ts
More file actions
1135 lines (1039 loc) · 34.2 KB
/
local-databases-ui.ts
File metadata and controls
1135 lines (1039 loc) · 34.2 KB
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, basename, dirname as path_dirname } from "path";
import { DisposableObject } from "../common/disposable-object";
import type {
Event,
ProviderResult,
TreeDataProvider,
CancellationToken,
QuickPickItem,
} from "vscode";
import {
EventEmitter,
TreeItem,
Uri,
window,
env,
ThemeIcon,
ThemeColor,
workspace,
FileType,
} from "vscode";
import { pathExists, stat, readdir, remove } from "fs-extra";
import type {
DatabaseChangedEvent,
DatabaseItem,
DatabaseManager,
} from "./local-databases";
import type { ProgressCallback } from "../common/vscode/progress";
import {
UserCancellationException,
withProgress,
} from "../common/vscode/progress";
import {
isLikelyDatabaseRoot,
isLikelyDbLanguageFolder,
} from "./local-databases/db-contents-heuristics";
import {
showAndLogExceptionWithTelemetry,
showAndLogErrorMessage,
showAndLogInformationMessage,
} from "../common/logging";
import type { DatabaseFetcher } from "./database-fetcher";
import { asError, asyncFilter, getErrorMessage } from "../common/helpers-pure";
import type { QueryRunner } from "../query-server";
import type { App } from "../common/app";
import { redactableError } from "../common/errors";
import type { LocalDatabasesCommands } from "../common/commands";
import {
createMultiSelectionCommand,
createSingleSelectionCommand,
} from "../common/vscode/selection-commands";
import {
getLanguageDisplayName,
tryGetQueryLanguage,
} from "../common/query-language";
import type { LanguageContextStore } from "../language-context-store";
enum SortOrder {
NameAsc = "NameAsc",
NameDesc = "NameDesc",
LanguageAsc = "LanguageAsc",
LanguageDesc = "LanguageDesc",
DateAddedAsc = "DateAddedAsc",
DateAddedDesc = "DateAddedDesc",
}
/**
* Tree data provider for the databases view.
*/
class DatabaseTreeDataProvider
extends DisposableObject
implements TreeDataProvider<DatabaseItem>
{
private _sortOrder = SortOrder.NameAsc;
private readonly _onDidChangeTreeData = this.push(
new EventEmitter<DatabaseItem | undefined>(),
);
private currentDatabaseItem: DatabaseItem | undefined;
constructor(
private databaseManager: DatabaseManager,
private languageContext: LanguageContextStore,
) {
super();
this.currentDatabaseItem = databaseManager.currentDatabaseItem;
this.push(
this.databaseManager.onDidChangeDatabaseItem(
this.handleDidChangeDatabaseItem.bind(this),
),
);
this.push(
this.databaseManager.onDidChangeCurrentDatabaseItem(
this.handleDidChangeCurrentDatabaseItem.bind(this),
),
);
this.push(
this.languageContext.onLanguageContextChanged(async () => {
this._onDidChangeTreeData.fire(undefined);
}),
);
}
public get onDidChangeTreeData(): Event<DatabaseItem | undefined> {
return this._onDidChangeTreeData.event;
}
private handleDidChangeDatabaseItem(event: DatabaseChangedEvent): void {
// Note that events from the database manager are instances of DatabaseChangedEvent
// and events fired by the UI are instances of DatabaseItem
// When a full refresh has occurred, then all items are refreshed by passing undefined.
this._onDidChangeTreeData.fire(event.fullRefresh ? undefined : event.item);
}
private handleDidChangeCurrentDatabaseItem(
event: DatabaseChangedEvent,
): void {
if (this.currentDatabaseItem) {
this._onDidChangeTreeData.fire(this.currentDatabaseItem);
}
this.currentDatabaseItem = event.item;
if (this.currentDatabaseItem) {
this._onDidChangeTreeData.fire(this.currentDatabaseItem);
}
}
public getTreeItem(element: DatabaseItem): TreeItem {
const item = new TreeItem(element.name);
if (element === this.currentDatabaseItem) {
item.iconPath = new ThemeIcon("check");
item.contextValue = "currentDatabase";
} else if (element.error !== undefined) {
item.iconPath = new ThemeIcon("error", new ThemeColor("errorForeground"));
}
item.tooltip = element.databaseUri.fsPath;
item.description =
element.language + (element.origin?.type === "testproj" ? " (test)" : "");
return item;
}
public getChildren(element?: DatabaseItem): ProviderResult<DatabaseItem[]> {
if (element === undefined) {
// Filter items by language
const displayItems = this.databaseManager.databaseItems.filter((item) => {
return this.languageContext.shouldInclude(
tryGetQueryLanguage(item.language),
);
});
// Sort items
return displayItems.slice(0).sort((db1, db2) => {
switch (this.sortOrder) {
case SortOrder.NameAsc:
return db1.name.localeCompare(db2.name, env.language);
case SortOrder.NameDesc:
return db2.name.localeCompare(db1.name, env.language);
case SortOrder.LanguageAsc:
return (
db1.language.localeCompare(db2.language, env.language) ||
// If the languages are the same, sort by name
db1.name.localeCompare(db2.name, env.language)
);
case SortOrder.LanguageDesc:
return (
db2.language.localeCompare(db1.language, env.language) ||
// If the languages are the same, sort by name
db2.name.localeCompare(db1.name, env.language)
);
case SortOrder.DateAddedAsc:
return (db1.dateAdded || 0) - (db2.dateAdded || 0);
case SortOrder.DateAddedDesc:
return (db2.dateAdded || 0) - (db1.dateAdded || 0);
}
});
} else {
return [];
}
}
public getParent(_element: DatabaseItem): ProviderResult<DatabaseItem> {
return null;
}
public getCurrent(): DatabaseItem | undefined {
return this.currentDatabaseItem;
}
public get sortOrder() {
return this._sortOrder;
}
public set sortOrder(newSortOrder: SortOrder) {
this._sortOrder = newSortOrder;
this._onDidChangeTreeData.fire(undefined);
}
}
/** Gets the first element in the given list, if any, or undefined if the list is empty or undefined. */
function getFirst(list: Uri[] | undefined): Uri | undefined {
if (list === undefined || list.length === 0) {
return undefined;
} else {
return list[0];
}
}
/**
* Displays file selection dialog. Expects the user to choose a
* database directory, which should be the parent directory of a
* directory of the form `db-[language]`, for example, `db-cpp`.
*
* XXX: no validation is done other than checking the directory name
* to make sure it really is a database directory.
*/
async function chooseDatabaseDir(byFolder: boolean): Promise<Uri | undefined> {
const chosen = await window.showOpenDialog({
openLabel: byFolder ? "Choose Database folder" : "Choose Database archive",
canSelectFiles: !byFolder,
canSelectFolders: byFolder,
canSelectMany: false,
filters: byFolder ? {} : { Archives: ["zip"] },
});
return getFirst(chosen);
}
export interface DatabaseSelectionQuickPickItem extends QuickPickItem {
databaseKind: "new" | "existing";
}
export interface DatabaseQuickPickItem extends QuickPickItem {
databaseItem: DatabaseItem;
}
export interface DatabaseImportQuickPickItems extends QuickPickItem {
importType: "URL" | "github" | "archive" | "folder";
}
export class DatabaseUI extends DisposableObject {
private treeDataProvider: DatabaseTreeDataProvider;
public constructor(
private app: App,
private databaseManager: DatabaseManager,
private readonly databaseFetcher: DatabaseFetcher,
languageContext: LanguageContextStore,
private readonly queryServer: QueryRunner,
private readonly storagePath: string,
readonly extensionPath: string,
) {
super();
this.treeDataProvider = this.push(
new DatabaseTreeDataProvider(databaseManager, languageContext),
);
this.push(
window.createTreeView("codeQLDatabases", {
treeDataProvider: this.treeDataProvider,
canSelectMany: true,
}),
);
}
public getCommands(): LocalDatabasesCommands {
return {
"codeQL.getCurrentDatabase": this.handleGetCurrentDatabase.bind(this),
"codeQL.chooseDatabaseFolder":
this.handleChooseDatabaseFolderFromPalette.bind(this),
"codeQL.chooseDatabaseFoldersParent":
this.handleChooseDatabaseFoldersParentFromPalette.bind(this),
"codeQL.chooseDatabaseArchive":
this.handleChooseDatabaseArchiveFromPalette.bind(this),
"codeQL.chooseDatabaseInternet":
this.handleChooseDatabaseInternet.bind(this),
"codeQL.chooseDatabaseGithub": this.handleChooseDatabaseGithub.bind(this),
"codeQL.setCurrentDatabase": this.handleSetCurrentDatabase.bind(this),
"codeQL.importTestDatabase": this.handleImportTestDatabase.bind(this),
"codeQL.setDefaultTourDatabase":
this.handleSetDefaultTourDatabase.bind(this),
"codeQL.upgradeCurrentDatabase":
this.handleUpgradeCurrentDatabase.bind(this),
"codeQL.clearCache": this.handleClearCache.bind(this),
"codeQL.trimCache": this.handleTrimCache.bind(this),
"codeQL.trimOverlayBaseCache": this.handleTrimOverlayBaseCache.bind(this),
"codeQLDatabases.chooseDatabaseFolder":
this.handleChooseDatabaseFolder.bind(this),
"codeQLDatabases.chooseDatabaseArchive":
this.handleChooseDatabaseArchive.bind(this),
"codeQLDatabases.chooseDatabaseInternet":
this.handleChooseDatabaseInternet.bind(this),
"codeQLDatabases.chooseDatabaseGithub":
this.handleChooseDatabaseGithub.bind(this),
"codeQLDatabases.setCurrentDatabase":
this.handleMakeCurrentDatabase.bind(this),
"codeQLDatabases.sortByName": this.handleSortByName.bind(this),
"codeQLDatabases.sortByLanguage": this.handleSortByLanguage.bind(this),
"codeQLDatabases.sortByDateAdded": this.handleSortByDateAdded.bind(this),
"codeQLDatabases.removeDatabase": createMultiSelectionCommand(
this.handleRemoveDatabase.bind(this),
),
"codeQLDatabases.upgradeDatabase": createMultiSelectionCommand(
this.handleUpgradeDatabase.bind(this),
),
"codeQLDatabases.renameDatabase": createSingleSelectionCommand(
this.app.logger,
this.handleRenameDatabase.bind(this),
"database",
),
"codeQLDatabases.openDatabaseFolder": createMultiSelectionCommand(
this.handleOpenFolder.bind(this),
),
"codeQLDatabases.addDatabaseSource": createMultiSelectionCommand(
this.handleAddSource.bind(this),
),
"codeQLDatabases.removeOrphanedDatabases":
this.handleRemoveOrphanedDatabases.bind(this),
};
}
private async handleMakeCurrentDatabase(
databaseItem: DatabaseItem,
): Promise<void> {
await this.databaseManager.setCurrentDatabaseItem(databaseItem);
}
private async chooseDatabaseFolder(
progress: ProgressCallback,
): Promise<void> {
try {
await this.chooseAndSetDatabase(true, progress);
} catch (e) {
void showAndLogExceptionWithTelemetry(
this.app.logger,
this.app.telemetry,
redactableError(
asError(e),
)`Failed to choose and set database: ${getErrorMessage(e)}`,
);
}
}
private async handleChooseDatabaseFolder(): Promise<void> {
return withProgress(
async (progress) => {
await this.chooseDatabaseFolder(progress);
},
{
title: "Adding database from folder",
},
);
}
private async handleChooseDatabaseFolderFromPalette(): Promise<void> {
return withProgress(
async (progress) => {
await this.chooseDatabaseFolder(progress);
},
{
title: "Choose a Database from a Folder",
},
);
}
private async handleChooseDatabaseFoldersParentFromPalette(): Promise<void> {
return withProgress(async (progress) => {
await this.chooseDatabasesParentFolder(progress);
});
}
private async handleSetDefaultTourDatabase(): Promise<void> {
return withProgress(
async () => {
try {
if (!workspace.workspaceFolders?.length) {
throw new Error("No workspace folder is open.");
} else {
// This specifically refers to the database folder in
// https://github.com/github/codespaces-codeql
const uri = Uri.parse(
`${workspace.workspaceFolders[0].uri.toString()}/.tours/codeql-tutorial-database`,
);
const databaseItem = this.databaseManager.findDatabaseItem(uri);
if (databaseItem === undefined) {
const makeSelected = true;
const nameOverride = "CodeQL Tutorial Database";
await this.databaseManager.openDatabase(
uri,
{
type: "folder",
},
makeSelected,
nameOverride,
{
isTutorialDatabase: true,
},
);
}
await this.handleTourDependencies();
}
} catch (e) {
// rethrow and let this be handled by default error handling.
throw new Error(
`Could not set the database for the Code Tour. Please make sure you are using the default workspace in your codespace: ${getErrorMessage(
e,
)}`,
);
}
},
{
title: "Set Default Database for Codespace CodeQL Tour",
},
);
}
private async handleTourDependencies(): Promise<void> {
if (!workspace.workspaceFolders?.length) {
throw new Error("No workspace folder is open.");
} else {
const tutorialQueriesPath = join(
workspace.workspaceFolders[0].uri.fsPath,
"tutorial-queries",
);
const cli = this.queryServer.cliServer;
await cli.packInstall(tutorialQueriesPath);
}
}
// Public because it's used in tests
public async handleRemoveOrphanedDatabases(): Promise<void> {
void this.app.logger.log(
"Removing orphaned databases from workspace storage.",
);
let dbDirs = undefined;
if (
!(await pathExists(this.storagePath)) ||
!(await stat(this.storagePath)).isDirectory()
) {
void this.app.logger.log(
"Missing or invalid storage directory. Not trying to remove orphaned databases.",
);
return;
}
dbDirs =
// read directory
(await readdir(this.storagePath, { withFileTypes: true }))
// remove non-directories
.filter((dirent) => dirent.isDirectory())
// get the full path
.map((dirent) => join(this.storagePath, dirent.name))
// remove databases still in workspace
.filter((dbDir) => {
const dbUri = Uri.file(dbDir);
return this.databaseManager.databaseItems.every(
(item) => item.databaseUri.fsPath !== dbUri.fsPath,
);
});
// remove non-databases
dbDirs = await asyncFilter(dbDirs, isLikelyDatabaseRoot);
if (!dbDirs.length) {
void this.app.logger.log("No orphaned databases found.");
return;
}
// delete
const failures = [] as string[];
await Promise.all(
dbDirs.map(async (dbDir) => {
try {
void this.app.logger.log(`Deleting orphaned database '${dbDir}'.`);
await remove(dbDir);
} catch (e) {
void showAndLogExceptionWithTelemetry(
this.app.logger,
this.app.telemetry,
redactableError(
asError(e),
)`Failed to delete orphaned database: ${getErrorMessage(e)}`,
);
failures.push(`${basename(dbDir)}`);
}
}),
);
if (failures.length) {
const dirname = path_dirname(failures[0]);
void showAndLogErrorMessage(
this.app.logger,
`Failed to delete unused databases (${failures.join(
", ",
)}).\nTo delete unused databases, please remove them manually from the storage folder ${dirname}.`,
);
}
}
private async chooseDatabaseArchive(
progress: ProgressCallback,
): Promise<void> {
try {
await this.chooseAndSetDatabase(false, progress);
} catch (e) {
void showAndLogExceptionWithTelemetry(
this.app.logger,
this.app.telemetry,
redactableError(
asError(e),
)`Failed to choose and set database: ${getErrorMessage(e)}`,
);
}
}
private async handleChooseDatabaseArchive(): Promise<void> {
return withProgress(
async (progress) => {
await this.chooseDatabaseArchive(progress);
},
{
title: "Adding database from archive",
},
);
}
private async handleChooseDatabaseArchiveFromPalette(): Promise<void> {
return withProgress(
async (progress) => {
await this.chooseDatabaseArchive(progress);
},
{
title: "Choose a Database from an Archive",
},
);
}
private async handleChooseDatabaseInternet(): Promise<void> {
return withProgress(
async (progress) => {
await this.databaseFetcher.promptImportInternetDatabase(progress);
},
{
title: "Adding database from URL",
},
);
}
private async handleChooseDatabaseGithub(): Promise<void> {
return withProgress(
async (progress) => {
await this.databaseFetcher.promptImportGithubDatabase(progress);
},
{
title: "Adding database from GitHub",
},
);
}
private async handleSortByName() {
if (this.treeDataProvider.sortOrder === SortOrder.NameAsc) {
this.treeDataProvider.sortOrder = SortOrder.NameDesc;
} else {
this.treeDataProvider.sortOrder = SortOrder.NameAsc;
}
}
private async handleSortByLanguage() {
if (this.treeDataProvider.sortOrder === SortOrder.LanguageAsc) {
this.treeDataProvider.sortOrder = SortOrder.LanguageDesc;
} else {
this.treeDataProvider.sortOrder = SortOrder.LanguageAsc;
}
}
private async handleSortByDateAdded() {
if (this.treeDataProvider.sortOrder === SortOrder.DateAddedAsc) {
this.treeDataProvider.sortOrder = SortOrder.DateAddedDesc;
} else {
this.treeDataProvider.sortOrder = SortOrder.DateAddedAsc;
}
}
private async handleUpgradeCurrentDatabase(): Promise<void> {
return withProgress(
async (progress, token) => {
if (this.databaseManager.currentDatabaseItem !== undefined) {
await this.handleUpgradeDatabasesInternal(progress, token, [
this.databaseManager.currentDatabaseItem,
]);
}
},
{
title: "Upgrading current database",
cancellable: true,
},
);
}
private async handleUpgradeDatabase(
databaseItems: DatabaseItem[],
): Promise<void> {
return withProgress(
async (progress, token) => {
return await this.handleUpgradeDatabasesInternal(
progress,
token,
databaseItems,
);
},
{
title: "Upgrading database",
cancellable: true,
},
);
}
private async handleUpgradeDatabasesInternal(
progress: ProgressCallback,
token: CancellationToken,
databaseItems: DatabaseItem[],
): Promise<void> {
await Promise.all(
databaseItems.map(async (databaseItem) => {
if (this.queryServer === undefined) {
throw new Error(
"Received request to upgrade database, but there is no running query server.",
);
}
if (databaseItem.contents === undefined) {
throw new Error(
"Received request to upgrade database, but database contents could not be found.",
);
}
if (databaseItem.contents.dbSchemeUri === undefined) {
throw new Error(
"Received request to upgrade database, but database has no schema.",
);
}
// Search for upgrade scripts in any workspace folders available
await this.queryServer.upgradeDatabaseExplicit(
databaseItem,
progress,
token,
);
}),
);
}
private async handleClearCache(): Promise<void> {
return withProgress(
async () => {
if (
this.queryServer !== undefined &&
this.databaseManager.currentDatabaseItem !== undefined
) {
await this.queryServer.clearCacheInDatabase(
this.databaseManager.currentDatabaseItem,
);
}
},
{
title: "Clearing cache",
},
);
}
private async handleTrimCache(): Promise<void> {
return withProgress(
async () => {
if (
this.queryServer !== undefined &&
this.databaseManager.currentDatabaseItem !== undefined
) {
await this.queryServer.trimCacheInDatabase(
this.databaseManager.currentDatabaseItem,
);
}
},
{
title: "Trimming cache",
},
);
}
private async handleTrimOverlayBaseCache(): Promise<void> {
return withProgress(
async () => {
if (
this.queryServer !== undefined &&
this.databaseManager.currentDatabaseItem !== undefined
) {
await this.queryServer.trimCacheWithModeInDatabase(
this.databaseManager.currentDatabaseItem,
"overlay",
);
}
},
{
title: "Removing all overlay-dependent data from cache",
},
);
}
private async handleGetCurrentDatabase(): Promise<string | undefined> {
const dbItem = await this.getDatabaseItemInternal(undefined);
return dbItem?.databaseUri.fsPath;
}
private async handleSetCurrentDatabase(uri: Uri): Promise<void> {
return withProgress(
async (progress) => {
try {
// Assume user has selected an archive if the file has a .zip extension
if (uri.path.endsWith(".zip")) {
await this.databaseFetcher.importLocalDatabase(
uri.toString(true),
progress,
);
} else {
await this.databaseManager.openDatabase(uri, {
type: "folder",
});
}
} catch (e) {
// rethrow and let this be handled by default error handling.
throw new Error(
`Could not set database to ${basename(
uri.fsPath,
)}. Reason: ${getErrorMessage(e)}`,
);
}
},
{
title: "Importing database from archive",
},
);
}
private async handleImportTestDatabase(uri: Uri): Promise<void> {
return withProgress(
async (progress) => {
try {
if (!uri.path.endsWith(".testproj")) {
throw new Error(
"Please select a valid test database to import. Test databases end with `.testproj`.",
);
}
// Check if the database is already in the workspace. If
// so, delete it first before importing the new one.
const existingItem = this.databaseManager.findTestDatabase(uri);
const baseName = basename(uri.fsPath);
if (existingItem !== undefined) {
progress({
maxStep: 9,
step: 1,
message: `Removing existing test database ${baseName}`,
});
await this.databaseManager.removeDatabaseItem(existingItem);
}
await this.databaseFetcher.importLocalDatabase(
uri.toString(true),
progress,
);
if (existingItem !== undefined) {
progress({
maxStep: 9,
step: 9,
message: `Successfully re-imported ${baseName}`,
});
}
} catch (e) {
// rethrow and let this be handled by default error handling.
throw new Error(
`Could not set database to ${basename(
uri.fsPath,
)}. Reason: ${getErrorMessage(e)}`,
);
}
},
{
title: "(Re-)importing test database from directory",
},
);
}
private async handleRemoveDatabase(
databaseItems: DatabaseItem[],
): Promise<void> {
return withProgress(
async () => {
await Promise.all(
databaseItems.map((dbItem) =>
this.databaseManager.removeDatabaseItem(dbItem),
),
);
},
{
title: "Removing database",
cancellable: false,
},
);
}
private async handleRenameDatabase(
databaseItem: DatabaseItem,
): Promise<void> {
const newName = await window.showInputBox({
prompt: "Choose new database name",
value: databaseItem.name,
});
if (newName) {
await this.databaseManager.renameDatabaseItem(databaseItem, newName);
}
}
private async handleOpenFolder(databaseItems: DatabaseItem[]): Promise<void> {
await Promise.all(
databaseItems.map((dbItem) => env.openExternal(dbItem.databaseUri)),
);
}
/**
* Adds the source folder of a CodeQL database to the workspace.
* When a database is first added in the "Databases" view, its source folder is added to the workspace.
* If the source folder is removed from the workspace for some reason, we want to be able to re-add it if need be.
*/
private async handleAddSource(databaseItems: DatabaseItem[]): Promise<void> {
for (const dbItem of databaseItems) {
await this.databaseManager.addDatabaseSourceArchiveFolder(dbItem);
}
}
/**
* Return the current database directory. If we don't already have a
* current database, ask the user for one, and return that, or
* undefined if they cancel.
*/
public async getDatabaseItem(
progress: ProgressCallback,
): Promise<DatabaseItem | undefined> {
return await this.getDatabaseItemInternal(progress);
}
/**
* Return the current database directory. If we don't already have a
* current database, ask the user for one, and return that, or
* undefined if they cancel.
*
* Unlike `getDatabaseItem()`, this function does not require the caller to pass in a progress
* context. If `progress` is `undefined`, then this command will create a new progress
* notification if it tries to perform any long-running operations.
*/
private async getDatabaseItemInternal(
progress: ProgressCallback | undefined,
): Promise<DatabaseItem | undefined> {
if (this.databaseManager.currentDatabaseItem === undefined) {
progress?.({
maxStep: 2,
step: 1,
message: "Choosing database",
});
await this.promptForDatabase();
}
return this.databaseManager.currentDatabaseItem;
}
private async promptForDatabase(): Promise<void> {
// If there aren't any existing databases,
// don't bother asking the user if they want to pick one.
if (this.databaseManager.databaseItems.length === 0) {
return this.importNewDatabase();
}
const quickPickItems: DatabaseSelectionQuickPickItem[] = [
{
label: "$(database) Existing database",
detail: "Select an existing database from your workspace",
alwaysShow: true,
databaseKind: "existing",
},
{
label: "$(arrow-down) New database",
detail:
"Import a new database from GitHub, a URL, or your local machine...",
alwaysShow: true,
databaseKind: "new",
},
];
const selectedOption =
await window.showQuickPick<DatabaseSelectionQuickPickItem>(
quickPickItems,
{
placeHolder: "Select an option",
ignoreFocusOut: true,
},
);
if (!selectedOption) {
throw new UserCancellationException("No database selected", true);
}
if (selectedOption.databaseKind === "existing") {
await this.selectExistingDatabase();
} else if (selectedOption.databaseKind === "new") {
await this.importNewDatabase();
}
}
private async selectExistingDatabase() {
const dbItems: DatabaseQuickPickItem[] =
this.databaseManager.databaseItems.map((dbItem) => ({
label: dbItem.name,
description: getLanguageDisplayName(dbItem.language),
databaseItem: dbItem,
}));
const selectedDatabase = await window.showQuickPick(dbItems, {
placeHolder: "Select an existing database from your workspace...",
ignoreFocusOut: true,
});
if (!selectedDatabase) {
throw new UserCancellationException("No database selected", true);
}
await this.databaseManager.setCurrentDatabaseItem(
selectedDatabase.databaseItem,
);
}
private async importNewDatabase() {
const importOptions: DatabaseImportQuickPickItems[] = [
{
label: "$(github) GitHub",
detail: "Import a database from a GitHub repository",
alwaysShow: true,
importType: "github",
},
{
label: "$(link) URL",
detail: "Import a database archive or folder from a remote URL",
alwaysShow: true,
importType: "URL",
},
{
label: "$(file-zip) Archive",
detail: "Import a database from a local ZIP archive",
alwaysShow: true,
importType: "archive",
},
{
label: "$(folder) Folder",
detail: "Import a database from a local folder",
alwaysShow: true,
importType: "folder",
},
];
const selectedImportOption =
await window.showQuickPick<DatabaseImportQuickPickItems>(importOptions, {
placeHolder:
"Import a new database from GitHub, a URL, or your local machine...",
ignoreFocusOut: true,
});
if (!selectedImportOption) {
throw new UserCancellationException("No database selected", true);
}
if (selectedImportOption.importType === "github") {
await this.handleChooseDatabaseGithub();
} else if (selectedImportOption.importType === "URL") {
await this.handleChooseDatabaseInternet();
} else if (selectedImportOption.importType === "archive") {
await this.handleChooseDatabaseArchive();
} else if (selectedImportOption.importType === "folder") {
await this.handleChooseDatabaseFolder();
}
}
/**
* Import database from uri. Returns the imported database, or `undefined` if the
* operation was unsuccessful or canceled.
*/
private async importDatabase(
uri: Uri,
byFolder: boolean,
progress: ProgressCallback,
): Promise<DatabaseItem | undefined> {
if (byFolder && !uri.fsPath.endsWith(".testproj")) {
const fixedUri = await this.fixDbUri(uri);
// we are selecting a database folder