-
Notifications
You must be signed in to change notification settings - Fork 526
Expand file tree
/
Copy pathpresetsController.ts
More file actions
1820 lines (1625 loc) · 88.1 KB
/
presetsController.ts
File metadata and controls
1820 lines (1625 loc) · 88.1 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 * as path from 'path';
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import * as lodash from "lodash";
import { CMakeProject, ConfigureTrigger, ConfigureType } from '@cmt/cmakeProject';
import * as logging from '@cmt/logging';
import { fs } from '@cmt/pr';
import * as preset from '@cmt/presets/preset';
import { PresetsParser } from '@cmt/presets/presetsParser';
import * as util from '@cmt/util';
import rollbar from '@cmt/rollbar';
import { ExpansionErrorHandler, ExpansionOptions } from '@cmt/expand';
import paths from '@cmt/paths';
import { KitsController } from '@cmt/kits/kitsController';
import { EnvironmentUtils } from '@cmt/environmentVariables';
import { descriptionForKit, Kit, SpecialKits } from '@cmt/kits/kit';
import { getHostTargetArchString } from '@cmt/installs/visualStudio';
import { Diagnostic, DiagnosticSeverity, Position, Range } from 'vscode';
import collections from '@cmt/diagnostics/collections';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
const log = logging.createLogger('presetController');
export class PresetsController implements vscode.Disposable {
private _presetsWatchers: FileWatcher | undefined;
private _sourceDirChangedSub: vscode.Disposable | undefined;
private _isChangingPresets = false;
// Populated by reapplyPresets() with paths of all preset files (CMakePresets.json,
// CMakeUserPresets.json, and any files pulled in via "include").
private _referencedFiles: string[] = [];
private _presetsParser!: PresetsParser; // Using definite assigment (!) because we initialize it in the init method
private _reapplyInProgress: Promise<void> = Promise.resolve();
private _suppressWatcherReapply: boolean = false;
private readonly _presetsChangedEmitter = new vscode.EventEmitter<preset.PresetsFile | undefined>();
private readonly _userPresetsChangedEmitter = new vscode.EventEmitter<preset.PresetsFile | undefined>();
private static readonly _addPreset = '__addPreset__';
static async init(project: CMakeProject, kitsController: KitsController, isMultiProject: boolean): Promise<PresetsController> {
const presetsController = new PresetsController(project, kitsController, isMultiProject);
const expandSourceDir = async (dir: string) => {
const workspaceFolder = project.workspaceFolder.uri.fsPath;
const expansionOpts: ExpansionOptions = {
vars: {
workspaceFolder,
workspaceFolderBasename: path.basename(workspaceFolder),
workspaceHash: util.makeHashString(workspaceFolder),
workspaceRoot: workspaceFolder,
workspaceRootFolderName: path.dirname(workspaceFolder),
userHome: paths.userHome,
// Following fields are not supported for sourceDir expansion
generator: '${generator}',
sourceDir: '${sourceDir}',
sourceParentDir: '${sourceParentDir}',
sourceDirName: '${sourceDirName}',
presetName: '${presetName}'
}
};
return util.normalizeAndVerifySourceDir(dir, expansionOpts);
};
presetsController._presetsParser = new PresetsParser(project.folderPath, await expandSourceDir(project.sourceDir), project.workspaceFolder.uri.fsPath, presetsController.reportPresetsFileErrors, presetsController.showPresetsFileVersionError, (filePath: string) => {
collections.presets.set(
vscode.Uri.file(filePath),
undefined
);
}, presetsController._presetsChangedEmitter.fire, presetsController._userPresetsChangedEmitter.fire);
// Pass cmake.environment and cmake.configureEnvironment settings so that $penv{} in preset
// include paths can resolve variables defined in VS Code settings.
presetsController.updateSettingsEnvironment();
// We explicitly read presets file here, instead of on the initialization of the file watcher. Otherwise
// there might be timing issues, since listeners are invoked async.
await presetsController.reapplyPresets();
project.workspaceContext.config.onChange('allowCommentsInPresetsFile', async () => {
await presetsController.reapplyPresets();
vscode.workspace.textDocuments.forEach(doc => {
const fileName = path.basename(doc.uri.fsPath);
if (fileName === 'CMakePresets.json' || fileName === 'CMakeUserPresets.json') {
if (project.workspaceContext.config.allowCommentsInPresetsFile) {
void vscode.languages.setTextDocumentLanguage(doc, 'jsonc');
} else {
void vscode.languages.setTextDocumentLanguage(doc, 'json');
}
}
});
});
project.workspaceContext.config.onChange('allowUnsupportedPresetsVersions', async () => {
await presetsController.reapplyPresets();
});
// We need to reapply presets to reassess whether the VS Developer Environment should be used.
project.workspaceContext.config.onChange('useVsDeveloperEnvironment', async () => {
await presetsController.reapplyPresets();
});
// We need to reapply presets when environment settings change so that $penv{} expansions
// in include paths are re-evaluated with the updated environment variables.
project.workspaceContext.config.onChange('environment', async () => {
presetsController.updateSettingsEnvironment();
await presetsController.reapplyPresets();
});
project.workspaceContext.config.onChange('configureEnvironment', async () => {
presetsController.updateSettingsEnvironment();
await presetsController.reapplyPresets();
});
return presetsController;
}
private constructor(private readonly project: CMakeProject, private readonly _kitsController: KitsController, private isMultiProject: boolean) {}
/**
* Merges cmake.environment and cmake.configureEnvironment settings into a single
* environment object and passes it to the PresetsParser for $penv{} expansion.
* cmake.configureEnvironment takes precedence over cmake.environment.
*/
private updateSettingsEnvironment(): void {
const env = this.project.workspaceContext.config.environment;
const configureEnv = this.project.workspaceContext.config.configureEnvironment;
this._presetsParser.settingsEnvironment = EnvironmentUtils.merge([env, configureEnv]);
}
get presetsPath() {
return this._presetsParser.presetsPath;
}
get userPresetsPath() {
return this._presetsParser.userPresetsPath;
}
get referencedFiles(): readonly string[] {
return this._referencedFiles;
}
/**
* When true, the file-watcher's change handler will not call reapplyPresets().
* Set this before saveAll() when the caller will explicitly await reapplyPresets()
* afterward, to avoid redundant re-reads triggered by the OS file-change
* notification for the same save (see #4792).
* Cleared automatically at the end of reapplyPresets().
*/
set suppressWatcherReapply(value: boolean) {
this._suppressWatcherReapply = value;
}
get workspaceFolder() {
return this.project.workspaceFolder;
}
get folderPath() {
return this.project.folderPath;
}
get folderName() {
return this.project.folderName;
}
get presetsFileExist() {
return this._presetsParser.presetsFileExists;
}
/**
* Updates the source directory used for locating CMakePresets.json and
* CMakeUserPresets.json, then reloads the presets from the new location.
* This is needed when the source directory changes after the PresetsController
* has already been initialized (e.g., when the user selects a CMakeLists.txt
* in a subdirectory via the missing-CMakeLists dialog).
*/
async updateSourceDir(sourceDir: string) {
this._presetsParser.sourceDir = sourceDir;
await this.reapplyPresets();
}
/**
* Call configurePresets, buildPresets, testPresets, packagePresets or workflowPresets to get the latest presets when thie event is fired.
*/
onPresetsChanged(listener: () => any) {
return this._presetsChangedEmitter.event(listener);
}
/**
* Call configurePresets, buildPresets, testPresets, packagePresets or workflowPresets to get the latest presets when thie event is fired.
*/
onUserPresetsChanged(listener: () => any) {
return this._userPresetsChangedEmitter.event(listener);
}
// Need to reapply presets every time presets changed since the binary dir or cmake path could change
// (need to clean or reload driver).
// Concurrent calls are serialized to avoid conflicts with the _isChangingPresets guard
// in setConfigurePreset and to ensure consistent preset state.
async reapplyPresets() {
const doReapply = async () => {
const referencedFiles: Map<string, preset.PresetsFile | undefined> =
new Map();
// Reset all changes due to expansion since parents could change
await this._presetsParser.resetPresetsFiles(
referencedFiles,
this.project.workspaceContext.config.allowCommentsInPresetsFile,
this.project.workspaceContext.config.allowUnsupportedPresetsVersions
);
// Collect the paths of all referenced preset files (main files + includes).
// resetPresetsFiles() populates the referencedFiles map as it parses each file.
this._referencedFiles = Array.from(referencedFiles.keys());
this.project.minCMakeVersion = preset.minCMakeVersion(this.folderPath);
if (this.project.configurePreset) {
await this.setConfigurePreset(this.project.configurePreset.name);
}
// Don't need to set build/test presets here since they are reapplied in setConfigurePreset
await this.watchPresetsChange();
// Clear after completing so that late watcher events from a
// prior saveAll() remain suppressed for the entire reapply.
this._suppressWatcherReapply = false;
};
this._reapplyInProgress = this._reapplyInProgress.then(doReapply, doReapply);
return this._reapplyInProgress;
}
private showNameInputBox() {
return vscode.window.showInputBox({ placeHolder: localize('preset.name', 'Preset name') });
}
private getOsName() {
const platmap = {
win32: 'Windows',
darwin: 'macOS',
linux: 'Linux'
} as { [k: string]: preset.OsName };
return platmap[process.platform];
}
async addConfigurePreset(quickStart?: boolean): Promise<boolean> {
const activeDocumentPath = vscode.window.activeTextEditor?.document.uri.fsPath;
interface AddPresetQuickPickItem extends vscode.QuickPickItem {
name: string;
}
enum SpecialOptions {
CreateFromCompilers = '__createFromCompilers__',
InheritConfigurationPreset = '__inheritConfigurationPreset__',
ToolchainFile = '__toolchainFile__',
Custom = '__custom__'
}
const items: AddPresetQuickPickItem[] = [];
if (preset.configurePresets(this.folderPath).length > 0) {
items.push({
name: SpecialOptions.InheritConfigurationPreset,
label: localize('inherit.config.preset', 'Inherit from Configure Preset'),
description: localize('description.inherit.config.preset', 'Inherit from an existing configure preset')
});
}
items.push({
name: SpecialOptions.CreateFromCompilers,
label: localize('create.from.compilers', 'Create from Compilers'),
description: localize('description.create.from.compilers', 'Create from a pair of compilers on this computer')
},
{
name: SpecialOptions.Custom,
label: localize('custom.config.preset', 'Custom'),
description: localize('description.custom.config.preset', 'Add a custom configure preset')
},
{
name: SpecialOptions.ToolchainFile,
label: localize('toolchain.file', 'Toolchain File'),
description: localize('description.toolchain.file', 'Configure with a CMake toolchain file')
});
const chosenItem = await vscode.window.showQuickPick(items,
{ placeHolder: localize('add.a.config.preset.placeholder', 'Add a configure preset for {0}', this.folderName) });
if (!chosenItem) {
log.debug(localize('user.cancelled.add.config.preset', 'User cancelled adding configure preset'));
return false;
} else {
let newPreset: preset.ConfigurePreset | undefined;
let isMultiConfigGenerator: boolean = false;
switch (chosenItem.name) {
case SpecialOptions.CreateFromCompilers: {
// Check that we have kits
if (!await this._kitsController.checkHaveKits()) {
return false;
}
const allKits = this._kitsController.availableKits;
// Filter VS based on generators, for example:
// VS 2019 Release x86, VS 2019 Preview x86, and VS 2017 Release x86
// will be filtered to
// VS 2019 x86, VS 2017 x86
// Remove toolchain kits
const filteredKits: Kit[] = [];
for (const kit of allKits) {
if (kit.toolchainFile || kit.name === SpecialKits.Unspecified) {
continue;
}
let duplicate = false;
if (kit.visualStudio && !kit.compilers) {
for (const filteredKit of filteredKits) {
if (filteredKit.preferredGenerator?.name === kit.preferredGenerator?.name &&
filteredKit.preferredGenerator?.platform === kit.preferredGenerator?.platform &&
filteredKit.preferredGenerator?.toolset === kit.preferredGenerator?.toolset) {
// Found same generator in the filtered list
duplicate = true;
break;
}
}
}
if (!duplicate) {
filteredKits.push(kit);
}
}
// if we are calling from quick start and no compilers are found, exit out with an error message
if (quickStart && filteredKits.length === 1 && filteredKits[0].name === SpecialKits.ScanForKits) {
log.debug(localize('no.compilers.available.for.quick.start', 'No compilers available for Quick Start'));
void vscode.window.showErrorMessage(
localize('no.compilers.available', 'Cannot generate a CmakePresets.json with Quick Start due to no compilers being available.'),
{
title: localize('learn.about.installing.compilers', 'Learn About Installing Compilers'),
isLearnMore: true
})
.then(async item => {
if (item && item.isLearnMore) {
await vscode.env.openExternal(vscode.Uri.parse('https://code.visualstudio.com/docs/languages/cpp#_install-a-compiler'));
}
});
return false;
}
log.debug(localize('start.selection.of.compilers', 'Start selection of compilers. Found {0} compilers.', filteredKits.length));
interface KitItem extends vscode.QuickPickItem {
kit: Kit;
}
log.debug(localize('opening.compiler.selection', 'Opening compiler selection QuickPick'));
// Generate the quickpick items from our known kits
const getKitName = (kit: Kit) => {
if (kit.name === SpecialKits.ScanForKits) {
return `[${localize('scan.for.compilers.button', 'Scan for compilers')}]`;
} else if (kit.visualStudio && !kit.compilers) {
const hostTargetArch = getHostTargetArchString(kit.visualStudioArchitecture!, kit.preferredGenerator?.platform);
return `${(kit.preferredGenerator?.name || 'Visual Studio')} ${hostTargetArch}`;
} else if (kit.name === SpecialKits.ScanSpecificDir) {
return `[${localize('scan.for.compilers.in.dir', 'Scan recursively for compilers in directory (max depth: 5)')}]`;
} else {
return kit.name;
}
};
const item_promises = filteredKits.map(
async (kit): Promise<KitItem> => ({
label: getKitName(kit),
description: await descriptionForKit(kit, true),
kit
})
);
const quickPickItems = await Promise.all(item_promises);
const chosen_kit = await vscode.window.showQuickPick(quickPickItems,
{ placeHolder: localize('select.a.compiler.placeholder', 'Select a Kit for {0}', this.folderName) });
if (chosen_kit === undefined) {
log.debug(localize('user.cancelled.compiler.selection', 'User cancelled compiler selection'));
// No selection was made
return false;
} else {
if (chosen_kit.kit.name === SpecialKits.ScanForKits) {
await KitsController.scanForKits(await this.project.getCMakePathofProject(), {
removeStaleCompilerKits: this.project.workspaceContext.config.removeStaleKitsOnScan
});
return false;
} else if (chosen_kit.kit.name === SpecialKits.ScanSpecificDir) {
await KitsController.scanForKitsInSpecificFolder(this.project);
return false;
} else {
log.debug(localize('user.selected.compiler', 'User selected compiler {0}', JSON.stringify(chosen_kit)));
const generator = chosen_kit.kit.preferredGenerator?.name;
const cacheVariables: { [key: string]: preset.CacheVarType | undefined } = {
CMAKE_INSTALL_PREFIX: '${sourceDir}/out/install/${presetName}',
CMAKE_C_COMPILER: chosen_kit.kit.compilers?.['C'] || (chosen_kit.kit.visualStudio ? 'cl.exe' : undefined),
CMAKE_CXX_COMPILER: chosen_kit.kit.compilers?.['CXX'] || (chosen_kit.kit.visualStudio ? 'cl.exe' : undefined)
};
if (util.isString(cacheVariables['CMAKE_C_COMPILER'])) {
cacheVariables['CMAKE_C_COMPILER'] = cacheVariables['CMAKE_C_COMPILER'].replace(/\\/g, '/');
}
if (util.isString(cacheVariables['CMAKE_CXX_COMPILER'])) {
cacheVariables['CMAKE_CXX_COMPILER'] = cacheVariables['CMAKE_CXX_COMPILER'].replace(/\\/g, '/');
}
isMultiConfigGenerator = util.isMultiConfGeneratorFast(generator);
if (!isMultiConfigGenerator) {
cacheVariables['CMAKE_BUILD_TYPE'] = 'Debug';
}
newPreset = {
name: '__placeholder__',
displayName: chosen_kit.kit.name,
description: chosen_kit.description,
generator,
toolset: chosen_kit.kit.preferredGenerator?.toolset,
architecture: chosen_kit.kit.preferredGenerator?.platform,
binaryDir: '${sourceDir}/out/build/${presetName}',
cacheVariables
};
}
}
break;
}
case SpecialOptions.InheritConfigurationPreset: {
const placeHolder = localize('select.one.or.more.config.preset.placeholder', 'Select one or more configure presets');
const presets = preset.allConfigurePresets(this.folderPath);
const inherits = await this.selectAnyPreset(presets, presets, { placeHolder, canPickMany: true });
newPreset = { name: '__placeholder__', description: '', displayName: '', inherits };
break;
}
case SpecialOptions.ToolchainFile: {
const displayName = localize("custom.configure.preset.toolchain.file", "Configure preset using toolchain file");
const description = localize("description.custom.configure.preset", "Sets Ninja generator, build and install directory");
newPreset = {
name: '__placeholder__',
displayName,
description,
generator: 'Ninja',
binaryDir: '${sourceDir}/out/build/${presetName}',
cacheVariables: {
CMAKE_BUILD_TYPE: 'Debug',
CMAKE_TOOLCHAIN_FILE: '',
CMAKE_INSTALL_PREFIX: '${sourceDir}/out/install/${presetName}'
}
};
break;
}
case SpecialOptions.Custom: {
const displayName = localize("custom.configure.preset", "Custom configure preset");
const description = localize("description.custom.configure.preset", "Sets Ninja generator, build and install directory");
newPreset = {
name: '__placeholder__',
displayName,
description,
generator: 'Ninja',
binaryDir: '${sourceDir}/out/build/${presetName}',
cacheVariables: {
CMAKE_BUILD_TYPE: 'Debug',
CMAKE_INSTALL_PREFIX: '${sourceDir}/out/install/${presetName}'
}
};
break;
}
default:
// Shouldn't reach here
break;
}
if (newPreset) {
const before: preset.ConfigurePreset[] = preset.allConfigurePresets(this.folderPath);
const name = await this.showNameInputBox() || newPreset.displayName || undefined;
if (!name) {
return false;
}
newPreset.name = name;
await this.addPresetAddUpdate(newPreset, 'configurePresets', activeDocumentPath);
// Ensure that we update our local copies of the PresetsFile so that adding the build preset happens as expected.
await this.reapplyPresets();
if (isMultiConfigGenerator) {
const buildPreset: preset.BuildPreset = {
name: `${newPreset.name}-debug`,
displayName: `${newPreset.displayName} - Debug`,
configurePreset: newPreset.name,
configuration: 'Debug'
};
await this.addPresetAddUpdate(buildPreset, 'buildPresets', activeDocumentPath);
}
if (before.length === 0) {
log.debug(localize('user.selected.config.preset', 'User selected configure preset {0}', JSON.stringify(newPreset.name)));
await this.setConfigurePreset(newPreset.name);
}
}
return true;
}
}
private async handleNoConfigurePresets(): Promise<boolean> {
const yes = localize('yes', 'Yes');
const no = localize('no', 'No');
const result = await vscode.window.showWarningMessage(
localize('no.config.preset', 'No Configure Presets exist. Would you like to add a Configure Preset?'), yes, no);
if (result === yes) {
return this.addConfigurePreset();
} else {
log.error(localize('error.no.config.preset', 'No configure presets exist.'));
return false;
}
}
async addBuildPreset(): Promise<boolean> {
const activeDocumentPath = vscode.window.activeTextEditor?.document.uri.fsPath;
if (preset.allConfigurePresets(this.folderPath).length === 0) {
return this.handleNoConfigurePresets();
}
interface AddPresetQuickPickItem extends vscode.QuickPickItem {
name: string;
}
enum SpecialOptions {
CreateFromConfigurationPreset = '__createFromConfigurationPreset__',
InheritBuildPreset = '__inheritBuildPreset__',
Custom = '__custom__'
}
const items: AddPresetQuickPickItem[] = [{
name: SpecialOptions.CreateFromConfigurationPreset,
label: localize('create.build.from.config.preset', 'Create from Configure Preset'),
description: localize('description.create.build.from.config.preset', 'Create a new build preset')
}];
if (preset.allBuildPresets(this.folderPath).length > 0) {
items.push({
name: SpecialOptions.InheritBuildPreset,
label: localize('inherit.build.preset', 'Inherit from Build Preset'),
description: localize('description.inherit.build.preset', 'Inherit from an existing build preset')
});
}
items.push({
name: SpecialOptions.Custom,
label: localize('custom.build.preset', 'Custom'),
description: localize('description.custom.build.preset', 'Add a custom build preset')
});
const chosenItem = await vscode.window.showQuickPick(items,
{ placeHolder: localize('add.a.build.preset.placeholder', 'Add a build preset for {0}', this.folderName) });
if (!chosenItem) {
log.debug(localize('user.cancelled.add.build.preset', 'User cancelled adding build preset'));
return false;
} else {
let newPreset: preset.BuildPreset | undefined;
switch (chosenItem.name) {
case SpecialOptions.CreateFromConfigurationPreset: {
const placeHolder = localize('select.a.config.preset.placeholder', 'Select a configure preset');
const presets = preset.allConfigurePresets(this.folderPath);
const configurePreset = await this.selectNonHiddenPreset(presets, presets, { placeHolder });
newPreset = { name: '__placeholder__', description: '', displayName: '', configurePreset };
break;
}
case SpecialOptions.InheritBuildPreset: {
const placeHolder = localize('select.one.or.more.build.preset.placeholder', 'Select one or more build presets');
const presets = preset.allBuildPresets(this.folderPath);
const inherits = await this.selectAnyPreset(presets, presets, { placeHolder, canPickMany: true });
newPreset = { name: '__placeholder__', description: '', displayName: '', inherits };
break;
}
case SpecialOptions.Custom: {
newPreset = { name: '__placeholder__', description: '', displayName: '' };
break;
}
default:
break;
}
if (newPreset) {
const name = await this.showNameInputBox();
if (!name) {
return false;
}
newPreset.name = name;
await this.addPresetAddUpdate(newPreset, 'buildPresets', activeDocumentPath);
}
return true;
}
}
async addTestPreset(): Promise<boolean> {
const activeDocumentPath = vscode.window.activeTextEditor?.document.uri.fsPath;
if (preset.allConfigurePresets(this.folderPath).length === 0) {
return this.handleNoConfigurePresets();
}
interface AddPresetQuickPickItem extends vscode.QuickPickItem {
name: string;
}
enum SpecialOptions {
CreateFromConfigurationPreset = '__createFromConfigurationPreset__',
InheritTestPreset = '__inheritTestPreset__',
Custom = '__custom__'
}
const items: AddPresetQuickPickItem[] = [{
name: SpecialOptions.CreateFromConfigurationPreset,
label: localize('create.test.from.config.preset', 'Create from Configure Preset'),
description: localize('description.create.test.from.config.preset', 'Create a new test preset')
}];
if (preset.allTestPresets(this.folderPath).length > 0) {
items.push({
name: SpecialOptions.InheritTestPreset,
label: localize('inherit.test.preset', 'Inherit from Test Preset'),
description: localize('description.inherit.test.preset', 'Inherit from an existing test preset')
});
}
items.push({
name: SpecialOptions.Custom,
label: localize('custom.test.preset', 'Custom'),
description: localize('description.custom.test.preset', 'Add a custom test preset')
});
const chosenItem = await vscode.window.showQuickPick(items,
{ placeHolder: localize('add.a.test.preset.placeholder', 'Add a test preset for {0}', this.folderName) });
if (!chosenItem) {
log.debug(localize('user.cancelled.add.test.preset', 'User cancelled adding test preset'));
return false;
} else {
let newPreset: preset.TestPreset | undefined;
switch (chosenItem.name) {
case SpecialOptions.CreateFromConfigurationPreset: {
const placeHolder = localize('select.a.config.preset.placeholder', 'Select a configure preset');
const presets = preset.allConfigurePresets(this.folderPath);
const configurePreset = await this.selectNonHiddenPreset(presets, presets, { placeHolder });
newPreset = { name: '__placeholder__', description: '', displayName: '', configurePreset };
break;
}
case SpecialOptions.InheritTestPreset: {
const placeHolder = localize('select.one.or.more.test.preset.placeholder', 'Select one or more test presets');
const presets = preset.allTestPresets(this.folderPath);
const inherits = await this.selectAnyPreset(presets, presets, { placeHolder, canPickMany: true });
newPreset = { name: '__placeholder__', description: '', displayName: '', inherits };
break;
}
case SpecialOptions.Custom: {
newPreset = { name: '__placeholder__', description: '', displayName: '' };
break;
}
default:
break;
}
if (newPreset) {
const name = await this.showNameInputBox();
if (!name) {
return false;
}
newPreset.name = name;
await this.addPresetAddUpdate(newPreset, 'testPresets', activeDocumentPath);
}
return true;
}
}
async addPackagePreset(): Promise<boolean> {
const activeDocumentPath = vscode.window.activeTextEditor?.document.uri.fsPath;
if (preset.allConfigurePresets(this.folderPath).length === 0) {
return this.handleNoConfigurePresets();
}
interface AddPresetQuickPickItem extends vscode.QuickPickItem {
name: string;
}
enum SpecialOptions {
CreateFromConfigurationPreset = '__createFromConfigurationPreset__',
InheritPackagePreset = '__inheritPackagePreset__',
Custom = '__custom__'
}
const items: AddPresetQuickPickItem[] = [{
name: SpecialOptions.CreateFromConfigurationPreset,
label: localize('create.package.from.config.preset', 'Create from Configure Preset'),
description: localize('description.create.package.from.config.preset', 'Create a new package preset')
}];
if (preset.packagePresets(this.folderPath).length > 0) {
items.push({
name: SpecialOptions.InheritPackagePreset,
label: localize('inherit.package.preset', 'Inherit from Package Preset'),
description: localize('description.inherit.package.preset', 'Inherit from an existing package preset')
});
}
items.push({
name: SpecialOptions.Custom,
label: localize('custom.package.preset', 'Custom'),
description: localize('description.custom.package.preset', 'Add a custom package preset')
});
const chosenItem = await vscode.window.showQuickPick(items,
{ placeHolder: localize('add.a.package.preset.placeholder', 'Add a package preset for {0}', this.folderName) });
if (!chosenItem) {
log.debug(localize('user.cancelled.add.package.preset', 'User cancelled adding package preset'));
return false;
} else {
let newPreset: preset.PackagePreset | undefined;
switch (chosenItem.name) {
case SpecialOptions.CreateFromConfigurationPreset: {
const placeHolder = localize('select.a.config.preset.placeholder', 'Select a configure preset');
const presets = preset.allConfigurePresets(this.folderPath);
const configurePreset = await this.selectNonHiddenPreset(presets, presets, { placeHolder });
newPreset = { name: '__placeholder__', description: '', displayName: '', configurePreset };
break;
}
case SpecialOptions.InheritPackagePreset: {
const placeHolder = localize('select.one.or.more.package.preset.placeholder', 'Select one or more package presets');
const presets = preset.packagePresets(this.folderPath);
const inherits = await this.selectAnyPreset(presets, presets, { placeHolder, canPickMany: true });
newPreset = { name: '__placeholder__', description: '', displayName: '', inherits };
break;
}
case SpecialOptions.Custom: {
newPreset = { name: '__placeholder__', description: '', displayName: '' };
break;
}
default:
break;
}
if (newPreset) {
const name = await this.showNameInputBox();
if (!name) {
return false;
}
newPreset.name = name;
await this.addPresetAddUpdate(newPreset, 'packagePresets', activeDocumentPath);
}
return true;
}
}
async addWorkflowPreset(): Promise<boolean> {
const activeDocumentPath = vscode.window.activeTextEditor?.document.uri.fsPath;
if (preset.allConfigurePresets(this.folderPath).length === 0) {
return this.handleNoConfigurePresets();
}
interface AddPresetQuickPickItem extends vscode.QuickPickItem {
name: string;
}
enum SpecialOptions {
// Will create a new workflow preset only with the first step of "configure" type
CreateFromConfigurationPreset = '__createFromConfigurationPreset__',
// This is not the usual "inheritance" that applies to all other types of presets,
// but only a convenient way of authoring a new preset from the content of another,
// instead of a plain copy-paste in the presets file.
// Also, inheritance can happen from multiple bases while this "create from" can start
// from only one base.
CreateFromWorkflowPreset = '__createFromWorkflowPreset__',
Custom = '__custom__'
}
const items: AddPresetQuickPickItem[] = [{
name: SpecialOptions.CreateFromConfigurationPreset,
label: localize('create.workflow.from.config.preset', 'Create from Configure Preset'),
description: localize('description.create.workflow.from.config.preset', 'Create a new workflow preset')
}];
if (preset.allWorkflowPresets(this.folderPath).length > 0) {
items.push({
name: SpecialOptions.CreateFromWorkflowPreset,
label: localize('create.workflow.preset', 'Create from Workflow Preset'),
description: localize('description.create.test.preset', 'Create a new workflow preset from an existing workflow preset')
});
}
items.push({
name: SpecialOptions.Custom,
label: localize('custom.workflow.preset', 'Custom'),
description: localize('description.custom.workflow.preset', 'Add a custom workflow preset')
});
const chosenItem = await vscode.window.showQuickPick(items,
{ placeHolder: localize('add.a.workflow.preset.placeholder', 'Add a workflow preset for {0}', this.folderName) });
if (!chosenItem) {
log.debug(localize('user.cancelled.add.workflow.preset', 'User cancelled adding workflow preset'));
return false;
} else {
let newPreset: preset.WorkflowPreset | undefined;
switch (chosenItem.name) {
case SpecialOptions.CreateFromConfigurationPreset: {
const placeHolder = localize('select.a.config.preset.placeholder', 'Select a configure preset');
const presets = preset.allConfigurePresets(this.folderPath);
const configurePreset = await this.selectNonHiddenPreset(presets, presets, { placeHolder });
if (configurePreset) {
newPreset = {
name: '__placeholder__', description: '', displayName: '',
steps: [{ type: "configure", name: configurePreset }]
};
}
break;
}
case SpecialOptions.CreateFromWorkflowPreset: {
const placeHolder = localize('select.one.workflow.preset.placeholder', 'Select one workflow base preset');
const presets = preset.allWorkflowPresets(this.folderPath);
const workflowBasePresetName = await this.selectNonHiddenPreset(presets, presets, { placeHolder, canPickMany: false });
const workflowBasePreset = presets.find(pr => pr.name === workflowBasePresetName);
newPreset = { name: '__placeholder__', description: '', displayName: '', steps: workflowBasePreset?.steps || [{ type: "configure", name: "_placeholder_" }] };
break;
}
case SpecialOptions.Custom: {
newPreset = { name: '__placeholder__', description: '', displayName: '', steps: [{ type: "configure", name: "_placeholder_" }] };
break;
}
default:
break;
}
if (newPreset) {
const name = await this.showNameInputBox();
if (!name) {
return false;
}
newPreset.name = name;
await this.addPresetAddUpdate(newPreset, 'workflowPresets', activeDocumentPath);
}
return true;
}
}
// Returns the name of preset selected from the list of non-hidden presets.
private async selectNonHiddenPreset(candidates: preset.Preset[], allPresets: preset.Preset[], options: vscode.QuickPickOptions): Promise<string | undefined> {
return this.selectPreset(candidates, allPresets, options, false);
}
// Returns the name of preset selected from the list of all hidden/non-hidden presets.
private async selectAnyPreset(candidates: preset.Preset[], allPresets: preset.Preset[], options: vscode.QuickPickOptions & { canPickMany: true }): Promise<string[] | undefined> {
return this.selectPreset(candidates, allPresets, options, true);
}
private async selectPreset(candidates: preset.Preset[], allPresets: preset.Preset[], options: vscode.QuickPickOptions & { canPickMany: true }, showHiddenPresets: boolean): Promise<string[] | undefined>;
private async selectPreset(candidates: preset.Preset[], allPresets: preset.Preset[], options: vscode.QuickPickOptions, showHiddenPresets: boolean): Promise<string | undefined>;
private async selectPreset(candidates: preset.Preset[], allPresets: preset.Preset[], options: vscode.QuickPickOptions, showHiddenPresets: boolean): Promise<string | string[] | undefined> {
interface PresetItem extends vscode.QuickPickItem {
preset: string;
}
const presetsPool: preset.Preset[] = showHiddenPresets ? candidates : candidates.filter(_preset => !_preset.hidden && preset.evaluatePresetCondition(_preset, allPresets));
const items: PresetItem[] = presetsPool.map(
_preset => ({
label: _preset.displayName || _preset.name,
description: _preset.description,
preset: _preset.name
})
);
items.push({
label: localize('add.new.preset', 'Add a New Preset...'),
preset: PresetsController._addPreset
});
const chosenPresets = await vscode.window.showQuickPick(items, options);
if (util.isArray<PresetItem>(chosenPresets)) {
return chosenPresets.map(_preset => _preset.preset);
}
return chosenPresets?.preset;
}
// For all of the `getAll` methods, we now can safely grab only the user presets (if present), because they inherently include
// the presets.
async getAllConfigurePresets(): Promise<preset.ConfigurePreset[]> {
const userPresets = preset.userConfigurePresets(this.folderPath);
return userPresets.length > 0 ? userPresets : preset.configurePresets(this.folderPath);
}
async getAllBuildPresets(): Promise<preset.BuildPreset[]> {
const userPresets = preset.userBuildPresets(this.folderPath);
return userPresets.length > 0 ? userPresets : preset.buildPresets(this.folderPath);
}
async getAllTestPresets(): Promise<preset.TestPreset[]> {
const userPresets = preset.userTestPresets(this.folderPath);
return userPresets.length > 0 ? userPresets : preset.testPresets(this.folderPath);
}
async getAllPackagePresets(): Promise<preset.PackagePreset[]> {
const userPresets = preset.userPackagePresets(this.folderPath);
return userPresets.length > 0 ? userPresets : preset.packagePresets(this.folderPath);
}
async getAllWorkflowPresets(): Promise<preset.WorkflowPreset[]> {
const userPresets = preset.userWorkflowPresets(this.folderPath);
return userPresets.length > 0 ? userPresets : preset.workflowPresets(this.folderPath);
}
async selectConfigurePreset(quickStart?: boolean): Promise<boolean> {
const allPresets: preset.ConfigurePreset[] = await this.getAllConfigurePresets();
const presets = allPresets.filter(
_preset => {
const supportedHost = (_preset.vendor as preset.VendorVsSettings)?.['microsoft.com/VisualStudioSettings/CMake/1.0']?.hostOS;
const osName = this.getOsName();
if (supportedHost) {
if (util.isString(supportedHost)) {
return supportedHost === osName;
} else {
return supportedHost.includes(osName);
}
} else {
return true;
}
}
);
log.debug(localize('start.selection.of.config.presets', 'Start selection of configure presets. Found {0} presets.', presets.length));
log.debug(localize('opening.config.preset.selection', 'Opening configure preset selection QuickPick'));
const placeHolder = localize('select.active.config.preset.placeholder', 'Select a configure preset for {0}', this.folderName);
const chosenPreset = await this.selectNonHiddenPreset(presets, allPresets, { placeHolder });
if (!chosenPreset) {
log.debug(localize('user.cancelled.config.preset.selection', 'User cancelled configure preset selection'));
return false;
} else if (chosenPreset === this.project.configurePreset?.name) {
return true;
} else {
const addPreset = chosenPreset === PresetsController._addPreset;
if (addPreset) {
await this.addConfigurePreset(quickStart);
} else {
log.debug(localize('user.selected.config.preset', 'User selected configure preset {0}', JSON.stringify(chosenPreset)));
await this.setConfigurePreset(chosenPreset);
}
if (this.project.workspaceContext.config.automaticReconfigure && !quickStart) {
await this.project.configureInternal(ConfigureTrigger.selectConfigurePreset, [], ConfigureType.Normal);
}
return !addPreset || allPresets.length === 0;
}
}
async setConfigurePreset(presetName: string): Promise<void> {
if (this._isChangingPresets) {
log.error(localize('preset.change.in.progress', 'A preset change is already in progress.'));
return;
}
this._isChangingPresets = true;
// Load the configure preset into the backend
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: localize('loading.config.preset', 'Loading configure preset {0}', presetName)
},
() => this.project.setConfigurePreset(presetName)
);
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: localize('reloading.build.test.preset', 'Reloading build and test presets')
},
async () => {
const configurePreset = this.project.configurePreset?.name;
const buildPreset = configurePreset ? this.project.workspaceContext.state.getBuildPresetName(this.project.folderName, configurePreset, this.isMultiProject) : undefined;
const testPreset = configurePreset ? this.project.workspaceContext.state.getTestPresetName(this.project.folderName, configurePreset, this.isMultiProject) : undefined;
const packagePreset = configurePreset ? this.project.workspaceContext.state.getPackagePresetName(this.project.folderName, configurePreset, this.isMultiProject) : undefined;
const workflowPreset = configurePreset ? this.project.workspaceContext.state.getWorkflowPresetName(this.project.folderName, configurePreset, this.isMultiProject) : undefined;
if (buildPreset) {
await this.setBuildPreset(buildPreset, true/*needToCheckConfigurePreset*/, false/*checkChangingPreset*/);
}
if (!buildPreset || !this.project.buildPreset) {
await this.guessBuildPreset();
}
if (testPreset) {
await this.setTestPreset(testPreset, true/*needToCheckConfigurePreset*/, false/*checkChangingPreset*/);
}
if (!testPreset || !this.project.testPreset) {
await this.guessTestPreset();
}
if (packagePreset) {
await this.setPackagePreset(packagePreset, true/*needToCheckConfigurePreset*/, false/*checkChangingPreset*/);
}
if (!packagePreset || !this.project.packagePreset) {
await this.guessPackagePreset();
}
if (workflowPreset) {
await this.setWorkflowPreset(workflowPreset, true/*needToCheckConfigurePreset*/, false/*checkChangingPreset*/);
}
if (!workflowPreset || !this.project.workflowPreset) {
await this.guessWorkflowPreset();
}
}
);
this._isChangingPresets = false;