-
Notifications
You must be signed in to change notification settings - Fork 534
Expand file tree
/
Copy pathpreset.ts
More file actions
2440 lines (2126 loc) · 113 KB
/
Copy pathpreset.ts
File metadata and controls
2440 lines (2126 loc) · 113 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
/* eslint-disable no-unused-expressions */
import * as nls from 'vscode-nls';
import * as path from 'path';
import * as vscode from "vscode";
import * as lodash from "lodash";
import * as api from 'vscode-cmake-tools';
import * as util from '@cmt/util';
import * as logging from '@cmt/logging';
import { execute } from '@cmt/proc';
import { errorHandlerHelper, expandString, ExpansionErrorHandler, ExpansionOptions } from '@cmt/expand';
import paths from '@cmt/paths';
import { compareVersions, VSInstallation, vsInstallations, enumerateMsvcToolsets, varsForVSInstallation, getVcVarsBatScript } from '@cmt/installs/visualStudio';
import { EnvironmentUtils, EnvironmentWithNull } from '@cmt/environmentVariables';
import { UseVsDeveloperEnvironment } from '@cmt/config';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
const log = logging.createLogger('preset');
export interface PresetsFile {
version: number;
schema?: string;
cmakeMinimumRequired?: util.Version;
include?: string[];
configurePresets?: ConfigurePreset[];
buildPresets?: BuildPreset[];
testPresets?: TestPreset[];
packagePresets?: PackagePreset[];
workflowPresets?: WorkflowPreset[];
__path?: string; // Private field holding the path to the file.
}
export type VendorType = { [key: string]: any };
export interface PresetPrivate {
__parentEnvironment?: EnvironmentWithNull; // Private field that contains the parent environment, which might be a modified VS Dev Env, or simply process.env.
__expanded?: boolean; // Private field to indicate if we have already expanded this preset.
__inheritedPresetCondition?: boolean; // Private field to indicate the fully evaluated inherited preset condition.
__file?: PresetsFile; // Private field to indicate the file where this preset was defined.
}
export interface Preset extends api.Preset, PresetPrivate {}
export type ValueStrategy = api.ValueStrategy;
export type CacheVarType = api.CacheVarType;
export interface WarningOptions {
dev?: boolean;
deprecated?: boolean;
uninitialized?: boolean;
unusedCli?: boolean;
systemVars?: boolean;
}
export interface ErrorOptions {
dev?: boolean;
deprecated?: boolean;
}
export interface DebugOptions {
output?: boolean;
tryCompile?: boolean;
find?: boolean;
}
enum TraceMode {
On = "on",
Off = "off",
Expand = "expand"
}
enum FormatMode {
Human = "human",
Json = "json-v1"
}
export interface Condition {
type: 'const' | 'equals' | 'notEquals' | 'inList' | 'notInList' | 'matches' | 'notMatches' | 'anyOf' | 'allOf' | 'not';
value?: boolean;
lhs?: string;
rhs?: string;
string?: string;
list?: string[];
regex?: string;
conditions?: Condition[];
condition?: Condition;
}
class MissingConditionPropertyError extends Error {
propertyName: string;
constructor(propertyName: string, ...params: any[]) {
super(...params);
this.propertyName = propertyName;
}
}
class InvalidConditionTypeError extends Error {
type: string;
constructor(type: string, ...params: any[]) {
super(...params);
this.type = type;
}
}
function validateConditionProperty(condition: Condition, propertyName: keyof Condition) {
const property: any = condition[propertyName];
if (property === undefined || property === null) {
throw new MissingConditionPropertyError(propertyName);
}
}
export function evaluateCondition(condition: Condition): boolean {
validateConditionProperty(condition, 'type');
switch (condition.type) {
case 'const':
validateConditionProperty(condition, 'value');
return condition.value!;
case 'equals':
case 'notEquals':
validateConditionProperty(condition, 'lhs');
validateConditionProperty(condition, 'rhs');
const equals = condition.lhs === condition.rhs;
return condition.type === 'equals' ? equals : !equals;
case 'inList':
case 'notInList':
validateConditionProperty(condition, 'string');
validateConditionProperty(condition, 'list');
const inList = condition.list!.includes(condition.string!);
return condition.type === 'inList' ? inList : !inList;
case 'matches':
case 'notMatches':
validateConditionProperty(condition, 'string');
validateConditionProperty(condition, 'regex');
const regex = new RegExp(condition.regex!);
const matches = regex.test(condition.string!);
return condition.type === 'matches' ? matches : !matches;
case 'allOf':
validateConditionProperty(condition, 'conditions');
return condition.conditions!.map((c) => evaluateCondition(c)).reduce((prev, current) => prev && current);
case 'anyOf':
validateConditionProperty(condition, 'conditions');
return condition.conditions!.map((c) => evaluateCondition(c)).reduce((prev, current) => prev || current);
case 'not':
validateConditionProperty(condition, 'condition');
return !evaluateCondition(condition.condition!);
default:
throw new InvalidConditionTypeError(condition.type);
}
}
function evaluateInheritedPresetConditions(preset: Preset, allPresets: Preset[], references: Set<string>): boolean | undefined {
const evaluateParent = (parentName: string) => {
const parent = getPresetByName(allPresets, parentName);
// If the child is not a user preset, the parent should not be a user preset.
// eslint-disable-next-line @typescript-eslint/tslint/config
if (parent && !preset.isUserPreset && parent.isUserPreset === true) {
log.error(localize('invalid.user.inherits', 'Preset {0} in CMakePresets.json can\'t inherit from preset {1} in CMakeUserPresets.json', preset.name, parentName));
return false;
}
if (parent && !references.has(parent.name)) {
parent.__inheritedPresetCondition = evaluatePresetCondition(parent, allPresets, references);
}
return parent ? parent.__inheritedPresetCondition : false;
};
references.add(preset.name);
if (preset.inherits) {
// When looking up inherited presets, default to false if the preset does not exist since this wouldn't
// be a valid preset to use.
if (util.isString(preset.inherits)) {
return evaluateParent(preset.inherits);
} else if (util.isArrayOfString(preset.inherits)) {
return preset.inherits.every(parentName => evaluateParent(parentName));
}
log.error(localize('invalid.inherits.type', 'Preset {0}: Invalid value for {1}', preset.name, `\"inherits\": "${preset.inherits}"`));
return false;
}
return true;
}
export function evaluatePresetCondition(preset: Preset, allPresets: Preset[], references?: Set<string>): boolean | undefined {
const condition = preset.condition;
if (condition === undefined && !evaluateInheritedPresetConditions(preset, allPresets, references || new Set<string>())) {
return false;
}
if (condition === undefined || condition === null) {
return true;
} else if (typeof condition === 'boolean') {
return condition;
} else if (typeof condition === 'object') {
try {
return evaluateCondition(condition);
} catch (e) {
if (e instanceof MissingConditionPropertyError) {
log.error(localize('missing.condition.property', 'Preset {0}: Missing required property {1} on condition object', preset.name, `"${e.propertyName}"`));
} else if (e instanceof InvalidConditionTypeError) {
log.error(localize('invalid.condition.type', 'Preset {0}: Invalid condition type {1}', preset.name, `"${e.type}"`));
} else {
// unexpected error
throw e;
}
return undefined;
}
}
log.error(localize('invalid.condition', 'Preset {0}: Condition must be null, boolean, or an object.', preset.name));
return undefined;
}
export type OsName = "Windows" | "Linux" | "macOS";
export type VendorVsSettings = {
'microsoft.com/VisualStudioSettings/CMake/1.0': {
hostOS?: OsName | OsName[];
intelliSenseMode?: string;
sourceDir?: string;
vsInstanceVersion?: number;
[key: string]: any;
};
[key: string]: any;
};
export interface ConfigurePreset extends PresetPrivate, api.ConfigurePreset {
// Private fields
__developerEnvironmentArchitecture?: string; // Private field to indicate which VS Dev Env architecture we're using, if VS Dev Env is used.
}
export interface InheritsConfigurePreset extends api.InheritsConfigurePreset, PresetPrivate {}
export interface BuildPresetPrivate {
__binaryDir?: string; // Getting this from the config preset
__generator?: string; // Getting this from the config preset
__targets?: string | string[]; // This field is translated to build args, so we can overwrite the target arguments.
}
export interface BuildPreset extends api.BuildPreset, BuildPresetPrivate, PresetPrivate {}
/**
* Should NOT cache anything. Need to make a copy if any fields need to be changed.
*/
export const defaultBuildPreset: BuildPreset = {
name: '__defaultBuildPreset__',
displayName: localize('default.build.preset', '[Default]'),
description: localize('default.build.preset.description', 'An empty build preset that does not add any arguments')
};
export interface TestPresetPrivate {
__binaryDir?: string; // Getting this from the config preset
__generator?: string; // Getting this from the config preset
}
export interface TestPreset extends api.TestPreset, TestPresetPrivate, PresetPrivate {}
export interface PackagePresetPrivate {
__binaryDir?: string; // Getting this from the config preset
__generator?: string; // Getting this from the config preset
}
export interface PackagePreset extends api.PackagePreset, PackagePresetPrivate, PresetPrivate {}
export interface WorkflowStepsOptions {
type: string;
name: string;
}
export interface WorkflowPreset {
name: string;
displayName?: string;
description?: string;
vendor?: VendorType;
isUserPreset?: boolean;
steps: WorkflowStepsOptions[];
__vsDevEnvApplied?: boolean; // Private field to indicate if we have already applied the VS Dev Env.
__expanded?: boolean; // Private field to indicate if we have already expanded this preset.
__file?: PresetsFile; // Private field to indicate the file where this preset was defined.
}
// Interface for toolset options specified here: https://cmake.org/cmake/help/latest/variable/CMAKE_GENERATOR_TOOLSET.html
// The key names (left of '=') are removed and just the values are stored.
interface Toolset {
name?: string; // 'toolset', e.g. 'v141'
cuda?: string; // 'cuda=<version>|<path>'
host?: string; // 'host=<arch>'
version?: string; // 'version=<version>'
VCTargetsPath?: string; // 'VCTargetsPath=<path>'
}
/**
* Should NOT cache anything. Need to make a copy if any fields need to be changed.
*/
export const defaultTestPreset: TestPreset = {
name: '__defaultTestPreset__',
displayName: localize('default.test.preset', '[Default]'),
description: localize('default.test.preset.description', 'An empty test preset that does not add any arguments')
};
export const defaultPackagePreset: PackagePreset = {
name: '__defaultPackagePreset__',
displayName: localize('default.package.preset', '[Default]'),
description: localize('default.package.preset.description', 'An empty package preset that does not add any arguments')
};
export const defaultWorkflowPreset: WorkflowPreset = {
name: '__defaultWorkflowPreset__',
steps: [{type: "configure", name: "_placeholder_"}],
displayName: localize('default.workflow.preset', '[Default]'),
description: localize('default.workflow.preset.description', 'An empty workflow preset that does not add any arguments')
};
/**
* presetsFiles are stored here because expansions require access to other presets.
* Change event emitters are in presetsController.
*
* original*PresetsFile's are each used to keep a copy by **value**. They are used to update
* the presets files when new presets are added.
*
* *presetsFilesIncluded is used to store the original presets files with included files.
* They are used for expansion.
*
* expanded*PresetsFiles is used to cache the expanded presets files, without the VS dev env applied.
*/
// Map<fsPath, PresetsFile | undefined>
const originalPresetsFiles: Map<string, PresetsFile | undefined> = new Map();
const originalUserPresetsFiles: Map<string, PresetsFile | undefined> = new Map();
const presetsPlusIncluded: Map<string, PresetsFile | undefined> = new Map();
const userPresetsPlusIncluded: Map<string, PresetsFile | undefined> = new Map();
const expandedPresets: Map<string, PresetsFile | undefined> = new Map();
const expandedUserPresets: Map<string, PresetsFile | undefined> = new Map();
export function getOriginalPresetsFile(folder: string) {
return originalPresetsFiles.get(folder);
}
export function getOriginalUserPresetsFile(folder: string) {
return originalUserPresetsFiles.get(folder);
}
export function setOriginalPresetsFile(folder: string, presets: PresetsFile | undefined) {
originalPresetsFiles.set(folder, presets);
}
export function setOriginalUserPresetsFile(folder: string, presets: PresetsFile | undefined) {
originalUserPresetsFiles.set(folder, presets);
}
export function setPresetsPlusIncluded(folder: string, presets: PresetsFile | undefined) {
presetsPlusIncluded.set(folder, presets);
}
export function setUserPresetsHelper(presets: PresetsFile | undefined) {
if (presets) {
// for each condition of `isUserPreset`, if we don't find file.path, then we default to true like before.
if (presets.configurePresets) {
for (const configPreset of presets.configurePresets) {
configPreset.isUserPreset = configPreset.__file?.__path?.endsWith("CMakeUserPresets.json") ?? true;
}
}
if (presets.buildPresets) {
for (const buildPreset of presets.buildPresets) {
buildPreset.isUserPreset = buildPreset.__file?.__path?.endsWith("CMakeUserPresets.json") ?? true;
}
}
if (presets.testPresets) {
for (const testPreset of presets.testPresets) {
testPreset.isUserPreset = testPreset.__file?.__path?.endsWith("CMakeUserPresets.json") ?? true;
}
}
if (presets.packagePresets) {
for (const packagePreset of presets.packagePresets) {
packagePreset.isUserPreset = packagePreset.__file?.__path?.endsWith("CMakeUserPresets.json") ?? true;
}
}
if (presets.workflowPresets) {
for (const workflowPreset of presets.workflowPresets) {
workflowPreset.isUserPreset = workflowPreset.__file?.__path?.endsWith("CMakeUserPresets.json") ?? true;
}
}
}
}
export function setUserPresetsPlusIncluded(folder: string, presets: PresetsFile | undefined) {
setUserPresetsHelper(presets);
userPresetsPlusIncluded.set(folder, presets);
}
export function setExpandedPresets(folder: string, presets: PresetsFile | undefined) {
expandedPresets.set(folder, presets);
}
/**
* This function updates the cache in both the regular presets cache and user presets cache.
* However, this only updates the cache if the preset was already in the cache.
* @param folder Folder to grab the cached expanded presets for
* @param preset The updated preset to cache
* @param presetType Type of the preset.
*/
export function updateCachedExpandedPreset(folder: string, preset: Preset, presetType: 'configurePresets' | 'buildPresets' | 'testPresets' | 'packagePresets' | 'workflowPresets') {
const clonedPreset = lodash.cloneDeep(preset);
const expanded = expandedPresets.get(folder);
const userExpanded = expandedUserPresets.get(folder);
updateCachedExpandedPresethelper(expanded, clonedPreset, presetType);
updateCachedExpandedPresethelper(userExpanded, clonedPreset, presetType);
}
/**
* Updates the cache only if the preset was already present in the cache.
* Updates the cache in-place, the sorting of the list will remain the same.
* @param cache The cache to update.
* @param preset The updated preset to cache
* @param presetType Type of the preset.
* @returns void
*/
function updateCachedExpandedPresethelper(cache: PresetsFile | undefined, preset: Preset, presetType: 'configurePresets' | 'buildPresets' | 'testPresets' | 'packagePresets' | 'workflowPresets') {
// Exit early if the cache or the list of presets is undefined.
if (!cache || !cache[presetType]) {
return;
}
// Exit early if the cache doesn't contain the preset.
const index = cache[presetType]!.findIndex(p => p.name === preset.name);
if (index === -1) {
return;
}
// TODO: I'd like to try and figure out how to template this so that we don't have this logic duplicated for each if statement.
// We know that the list exists so we use "!".
// We use slice so that we can insert the updated preset in the same location it was previously in.
if (presetType === 'configurePresets') {
cache.configurePresets = [...cache.configurePresets!.slice(0, index), preset as ConfigurePreset, ...cache.configurePresets!.slice(index + 1)];
} else if (presetType === "buildPresets") {
cache.buildPresets = [...cache.buildPresets!.slice(0, index), preset as BuildPreset, ...cache.buildPresets!.slice(index + 1)];
} else if (presetType === "testPresets") {
cache.testPresets = [...cache.testPresets!.slice(0, index), preset as TestPreset, ...cache.testPresets!.slice(index + 1)];
} else if (presetType === "packagePresets") {
cache.packagePresets = [...cache.packagePresets!.slice(0, index), preset as PackagePreset, ...cache.packagePresets!.slice(index + 1)];
} else if (presetType === "workflowPresets") {
cache.workflowPresets = [...cache.workflowPresets!.slice(0, index), preset as WorkflowPreset, ...cache.workflowPresets!.slice(index + 1)];
}
}
export function setExpandedUserPresetsFile(folder: string, presets: PresetsFile | undefined) {
setUserPresetsHelper(presets);
expandedUserPresets.set(folder, presets);
}
export function minCMakeVersion(folder: string) {
const min1 = presetsPlusIncluded.get(folder)?.cmakeMinimumRequired;
const min2 = presetsPlusIncluded.get(folder)?.cmakeMinimumRequired;
if (!min1) {
return min2;
}
if (!min2) {
return min1;
}
// The combined minimum version is the higher version of the two
return util.versionLess(min1, min2) ? min2 : min1;
}
export function configurePresets(folder: string, usePresetsPlusIncluded: boolean = false) {
if (usePresetsPlusIncluded) {
return presetsPlusIncluded.get(folder)?.configurePresets || [];
}
return expandedPresets.get(folder)?.configurePresets || [];
}
export function userConfigurePresets(folder: string, usePresetsPlusIncluded: boolean = false) {
if (usePresetsPlusIncluded) {
return userPresetsPlusIncluded.get(folder)?.configurePresets || [];
}
return expandedUserPresets.get(folder)?.configurePresets || [];
}
/**
* Don't use this function if you need to keep any changes in the presets
*/
export function allConfigurePresets(folder: string, usePresetsPlusIncluded: boolean = false) {
return lodash.unionWith(configurePresets(folder, usePresetsPlusIncluded).concat(userConfigurePresets(folder, usePresetsPlusIncluded)), (a, b) => a.name === b.name);
}
export function buildPresets(folder: string, usePresetsPlusIncluded: boolean = false) {
if (usePresetsPlusIncluded) {
return presetsPlusIncluded.get(folder)?.buildPresets || [];
}
return expandedPresets.get(folder)?.buildPresets || [];
}
export function userBuildPresets(folder: string, usePresetsPlusIncluded: boolean = false) {
if (usePresetsPlusIncluded) {
return userPresetsPlusIncluded.get(folder)?.buildPresets || [];
}
return expandedUserPresets.get(folder)?.buildPresets || [];
}
/**
* Don't use this function if you need to keep any changes in the presets
*/
export function allBuildPresets(folder: string, usePresetsPlusIncluded: boolean = false) {
return lodash.unionWith(buildPresets(folder, usePresetsPlusIncluded).concat(userBuildPresets(folder, usePresetsPlusIncluded)), (a, b) => a.name === b.name);
}
export function testPresets(folder: string, usePresetsPlusIncluded: boolean = false) {
if (usePresetsPlusIncluded) {
return presetsPlusIncluded.get(folder)?.testPresets || [];
}
return expandedPresets.get(folder)?.testPresets || [];
}
export function userTestPresets(folder: string, usePresetsPlusIncluded: boolean = false) {
if (usePresetsPlusIncluded) {
return userPresetsPlusIncluded.get(folder)?.testPresets || [];
}
return expandedUserPresets.get(folder)?.testPresets || [];
}
/**
* Don't use this function if you need to keep any changes in the presets
*/
export function allTestPresets(folder: string, usePresetsPlusIncluded: boolean = false) {
return lodash.unionWith(testPresets(folder, usePresetsPlusIncluded).concat(userTestPresets(folder, usePresetsPlusIncluded)), (a, b) => a.name === b.name);
}
export function packagePresets(folder: string, usePresetsPlusIncluded: boolean = false) {
if (usePresetsPlusIncluded) {
return presetsPlusIncluded.get(folder)?.packagePresets || [];
}
return expandedPresets.get(folder)?.packagePresets || [];
}
export function userPackagePresets(folder: string, usePresetsPlusIncluded: boolean = false) {
if (usePresetsPlusIncluded) {
return userPresetsPlusIncluded.get(folder)?.packagePresets || [];
}
return expandedUserPresets.get(folder)?.packagePresets || [];
}
/**
* Don't use this function if you need to keep any changes in the presets
*/
export function allPackagePresets(folder: string, usePresetsPlusIncluded: boolean = false) {
return lodash.unionWith(packagePresets(folder, usePresetsPlusIncluded).concat(userPackagePresets(folder, usePresetsPlusIncluded)), (a, b) => a.name === b.name);
}
export function workflowPresets(folder: string, usePresetsPlusIncluded: boolean = false) {
if (usePresetsPlusIncluded) {
return presetsPlusIncluded.get(folder)?.workflowPresets || [];
}
return expandedPresets.get(folder)?.workflowPresets || [];
}
export function userWorkflowPresets(folder: string, usePresetsPlusIncluded: boolean = false) {
if (usePresetsPlusIncluded) {
return userPresetsPlusIncluded.get(folder)?.workflowPresets || [];
}
return expandedUserPresets.get(folder)?.workflowPresets || [];
}
/**
* Don't use this function if you need to keep any changes in the presets
*/
export function allWorkflowPresets(folder: string, usePresetsPlusIncluded: boolean = false) {
return lodash.unionWith(workflowPresets(folder, usePresetsPlusIncluded).concat(userWorkflowPresets(folder, usePresetsPlusIncluded)), (a, b) => a.name === b.name);
}
export function getPresetByName<T extends Preset>(presets: T[], name: string): T | null {
return presets.find(preset => preset.name === name) ?? null;
}
function isInheritable(key: keyof ConfigurePreset | keyof BuildPreset | keyof TestPreset | keyof PackagePreset | keyof WorkflowPreset) {
return key !== 'name' && key !== 'hidden' && key !== 'inherits' && key !== 'description' && key !== 'displayName';
}
export function inheritsFromUserPreset(preset: ConfigurePreset | BuildPreset | TestPreset | PackagePreset | WorkflowPreset,
presetType: 'configurePresets' | 'buildPresets' | 'testPresets' | 'packagePresets' | 'workflowPresets', folderPath: string): boolean {
const originalUserPresetsFile: PresetsFile = getOriginalUserPresetsFile(folderPath) || { version: 8 };
const presetInherits = (presets: Preset[] | undefined, inherits: string | string[] | undefined) => presets?.find(p =>
Array.isArray(inherits)
? inherits.some(inherit => inherit === p.name)
: inherits === p.name
);
if (presetType !== 'workflowPresets' && (preset as Preset).inherits &&
presetInherits(originalUserPresetsFile[presetType], (preset as Preset).inherits)) {
return true;
}
// first step of a Workflow Preset must be a configure preset
const inheritedConfigurePreset = presetType === 'workflowPresets' ? (preset as WorkflowPreset).steps[0]?.name :
presetType !== 'configurePresets' ? (preset as InheritsConfigurePreset).configurePreset : undefined;
return inheritedConfigurePreset ?
!!originalUserPresetsFile.configurePresets?.find(p => p.name === inheritedConfigurePreset) : false;
}
/**
* Shallow copy if a key in base doesn't exist in target
*/
function merge<T extends Object>(target: T, base: T) {
Object.keys(base).forEach(key => {
const field = key as keyof T;
if (!target.hasOwnProperty(field)) {
target[field] = base[field] as never;
}
});
}
/**
* Used for both expandConfigurePreset and expandVendorForConfigurePreset
* Map<fsPath, Set<referencedPresets>>
*/
const referencedConfigurePresets: Map<string, Set<string>> = new Map();
async function getVendorForConfigurePreset(folder: string, name: string, sourceDir: string, workspaceFolder: string, allowUserPreset: boolean = false, usePresetsPlusIncluded: boolean = false, errorHandler?: ExpansionErrorHandler): Promise<VendorType | VendorVsSettings | null> {
const refs = referencedConfigurePresets.get(folder);
if (!refs) {
referencedConfigurePresets.set(folder, new Set());
} else {
refs.clear();
}
return getVendorForConfigurePresetImpl(folder, name, sourceDir, workspaceFolder, allowUserPreset, usePresetsPlusIncluded, errorHandler);
}
async function getVendorForConfigurePresetImpl(folder: string, name: string, sourceDir: string, workspaceFolder: string, allowUserPreset: boolean = false, usePresetsPlusIncluded: boolean = false, errorHandler?: ExpansionErrorHandler): Promise<VendorType | VendorVsSettings | null> {
let preset = getPresetByName(configurePresets(folder, usePresetsPlusIncluded), name);
if (preset) {
return getVendorForConfigurePresetHelper(folder, preset, sourceDir, workspaceFolder, allowUserPreset, usePresetsPlusIncluded, errorHandler);
}
if (allowUserPreset) {
preset = getPresetByName(userConfigurePresets(folder, usePresetsPlusIncluded), name);
if (preset) {
return getVendorForConfigurePresetHelper(folder, preset, sourceDir, workspaceFolder, allowUserPreset, usePresetsPlusIncluded, errorHandler);
}
}
return null;
}
async function getVendorForConfigurePresetHelper(folder: string, preset: ConfigurePreset, sourceDir: string, workspaceFolder: string, allowUserPreset: boolean = false, usePresetsPlusIncluded: boolean = false, errorHandler?: ExpansionErrorHandler): Promise<VendorType | VendorVsSettings | null> {
if (preset.__expanded) {
return preset.vendor || null;
}
const refs = referencedConfigurePresets.get(folder)!;
if (refs.has(preset.name)) {
// Referenced this preset before, but it doesn't have a configure preset. This is a circular inheritance.
log.error(localize('circular.inherits.in.config.preset', 'Circular inherits in configure preset {0}', preset.name));
errorHandler?.errorList.push([localize('circular.inherits.in.config.preset', 'Circular inherits in configure preset'), preset.name]);
return null;
}
refs.add(preset.name);
preset.vendor = preset.vendor || {};
if (preset.inherits) {
if (util.isString(preset.inherits)) {
preset.inherits = [preset.inherits];
}
for (const parent of preset.inherits) {
const parentVendor = await getVendorForConfigurePresetImpl(folder, parent, sourceDir, workspaceFolder, usePresetsPlusIncluded, allowUserPreset);
if (parentVendor) {
for (const key in parentVendor) {
if (preset.vendor[key] === undefined) {
preset.vendor[key] = parentVendor[key];
}
}
}
}
}
return preset.vendor || null;
}
async function getExpansionOptions(workspaceFolder: string, sourceDir: string, preset: ConfigurePreset | BuildPreset | TestPreset | PackagePreset, envOverride?: EnvironmentWithNull, penvOverride?: EnvironmentWithNull, includeGenerator: boolean = true) {
const generator = includeGenerator ? 'generator' in preset
? preset.generator
: ('__generator' in preset ? preset.__generator : undefined) : undefined;
const expansionOpts: ExpansionOptions = {
vars: {
generator: generator || 'null',
workspaceFolder,
workspaceFolderBasename: path.basename(workspaceFolder),
workspaceHash: util.makeHashString(workspaceFolder),
workspaceRoot: workspaceFolder,
workspaceRootFolderName: path.dirname(workspaceFolder),
userHome: paths.userHome,
sourceDir,
sourceParentDir: path.dirname(sourceDir),
sourceDirName: path.basename(sourceDir),
presetName: preset.name
},
envOverride: envOverride ?? preset.environment,
penvOverride: penvOverride,
recursive: true,
// Don't support commands since expansion might be called on activation. If there is
// an extension depending on us, and there is a command in this extension is invoked,
// this would be a deadlock. This could be avoided but at a huge cost.
doNotSupportCommands: true
};
if (preset.__file && preset.__file.version >= 3) {
expansionOpts.vars.hostSystemName = await util.getHostSystemNameMemo();
}
if (preset.__file && preset.__file.version >= 4) {
expansionOpts.vars.fileDir = path.dirname(preset.__file!.__path!);
}
if (preset.__file && preset.__file.version >= 5) {
expansionOpts.vars.pathListSep = path.delimiter;
}
return expansionOpts;
}
async function expandCondition(condition: boolean | Condition | null | undefined, expansionOpts: ExpansionOptions, errorHandler?: ExpansionErrorHandler): Promise<boolean | Condition | undefined> {
if (util.isNullOrUndefined(condition)) {
return undefined;
}
if (util.isBoolean(condition)) {
return condition;
}
if (condition.type) {
const result: Condition = { type: condition.type };
if (condition.lhs) {
result.lhs = await expandString(condition.lhs, expansionOpts, errorHandler);
}
if (condition.rhs) {
result.rhs = await expandString(condition.rhs, expansionOpts, errorHandler);
}
if (condition.string) {
result.string = await expandString(condition.string, expansionOpts, errorHandler);
}
if (condition.list) {
result.list = [];
for (const value of condition.list) {
result.list.push(await expandString(value, expansionOpts, errorHandler));
}
}
if (condition.condition) {
const expanded = await expandCondition(condition.condition, expansionOpts);
if (!util.isBoolean(expanded)) {
result.condition = expanded;
}
}
if (condition.conditions) {
result.conditions = [];
for (const value of condition.conditions) {
const expanded = await expandCondition(value, expansionOpts);
if (expanded && !util.isBoolean(expanded)) {
result.conditions.push(expanded);
}
}
}
merge(result, condition); // Copy the remaining fields;
return result;
}
return undefined;
}
export function getArchitecture(preset: ConfigurePreset) {
if (util.isString(preset.architecture)) {
return preset.architecture;
} else if (preset.architecture && preset.architecture.value) {
return preset.architecture.value;
}
const fallbackArchitecture = util.getHostArchitecture();
log.warning(localize('no.cl.arch', 'Configure preset {0}: No architecture specified for cl.exe, using {1} by default', preset.name, fallbackArchitecture));
return fallbackArchitecture;
}
export function getToolset(preset: ConfigurePreset): Toolset {
let result: Toolset | undefined;
if (util.isString(preset.toolset)) {
result = parseToolset(preset.toolset);
} else if (preset.toolset && util.isString(preset.toolset.value)) {
result = parseToolset(preset.toolset.value);
}
const fallbackArchitecture = util.getHostArchitecture();
const noToolsetArchWarning = localize('no.cl.toolset.arch', "Configure preset {0}: No toolset architecture specified for cl.exe, using {1} by default", preset.name, `"host=${fallbackArchitecture}"`);
if (result) {
if (result.name === 'x86' || result.name === 'x64') {
log.warning(localize('invalid.cl.toolset.arch', "Configure preset {0}: Unexpected toolset architecture specified {1}, did you mean {2}?", preset.name, `"${result.name}"`, `"host=${result.name}"`));
}
if (!result.host) {
log.warning(noToolsetArchWarning);
result.host = fallbackArchitecture;
}
if (!result.version && result.name !== latestToolsetName) {
log.warning(localize('no.cl.toolset.version', 'Configure preset {0}: No toolset version specified for cl.exe, using latest by default', preset.name));
}
} else {
log.warning(noToolsetArchWarning);
result = { host: fallbackArchitecture };
}
return result;
}
const toolsetToVersion: { [key: string]: string } = {
'v100': '10.0',
'v110': '11.0',
'v120': '12.0',
'v140': '14.0',
'v141': '14.16',
'v142': '14.29'
// don't include the latest version - the compiler version changes frequently and it will be picked by default anyway.
// NOTE: the latest toolset name (below) should be kept up to date.
};
const latestToolsetName = 'v143';
// We don't support all of these options for Kit lookup right now, but might in the future.
function parseToolset(toolset: string): Toolset {
const toolsetOptions = toolset.split(',');
const result: Toolset = {};
for (const option of toolsetOptions) {
if (option.indexOf('=') < 0) {
const version = toolsetToVersion[option];
if (version) {
result.version = version;
} else {
result.name = option;
}
} else {
const keyValue = option.split('=');
switch (keyValue[0].toLowerCase()) {
case 'cuda':
result.cuda = keyValue[1];
break;
case 'host':
result.host = keyValue[1];
break;
case 'version':
result.version = keyValue[1];
break;
case 'vctargetspath':
result.VCTargetsPath = keyValue[1];
break;
default:
log.warning(localize('unknown.toolset.option', "Unrecognized toolset option will be ignored: {0}", option));
break;
}
}
}
return result;
}
export interface VsDevEnvOptions {
preset: ConfigurePreset;
shouldInterrogateForNinja: boolean;
compilerName?: string; // Only will have a value when `useVsDeveloperEnvironmentMode` is "auto"
}
export interface VsDevEnvAutoDetectionInfo {
compilerName?: string;
generatorIsNinja: boolean;
}
/**
* @param opts Options to control the behavior of obtaining the VS developer environment.
* @returns Either the VS developer environment or undefined if it could not be obtained.
*/
async function getVsDevEnv(opts: VsDevEnvOptions): Promise<EnvironmentWithNull | undefined> {
const arch = getArchitecture(opts.preset);
const toolset = getToolset(opts.preset);
// Get version info for all VS instances.
const vsInstalls = await vsInstallations();
// The VS installation to grab developer environment from.
let vsInstall: VSInstallation | undefined;
// VS generators starting with Visual Studio 15 2017 support CMAKE_GENERATOR_INSTANCE.
// If supported, we should respect this value when defined. If not defined, we should
// set it to ensure CMake chooses the same VS instance as we use here.
// Note that if the user sets this in a toolchain file we won't know about it,
// which could cause configuration to fail. However the user can workaround this by launching
// vscode from the dev prompt of their desired instance.
// https://cmake.org/cmake/help/latest/variable/CMAKE_GENERATOR_INSTANCE.html
let vsGeneratorVersion: number | undefined;
const matches = opts.preset.generator?.match(/Visual Studio (?<version>\d+)/);
if (opts.preset.cacheVariables && matches && matches.groups?.version) {
vsGeneratorVersion = parseInt(matches.groups.version);
const useCMakeGeneratorInstance = !isNaN(vsGeneratorVersion) && vsGeneratorVersion >= 15;
const cmakeGeneratorInstance = getStringValueFromCacheVar(opts.preset.cacheVariables['CMAKE_GENERATOR_INSTANCE']);
if (useCMakeGeneratorInstance && cmakeGeneratorInstance) {
const cmakeGeneratorInstanceNormalized = path.normalize(cmakeGeneratorInstance);
vsInstall = vsInstalls.find((vs) => vs.installationPath
&& path.normalize(vs.installationPath) === cmakeGeneratorInstanceNormalized);
if (!vsInstall) {
log.warning(localize('specified.vs.not.found',
"Configure preset {0}: Visual Studio instance specified by {1} was not found, falling back on default instance lookup behavior.",
opts.preset.name, `CMAKE_GENERATOR_INSTANCE="${cmakeGeneratorInstance}"`));
}
}
}
// If VS instance wasn't chosen using CMAKE_GENERATOR_INSTANCE, check the vendor field
// for a preferred VS major version (e.g., 17 for VS2022, 18 for VS2026).
// This allows users to pin a specific VS version for the dev environment in Ninja presets.
let vendorVsVersion: number | undefined;
if (!vsInstall) {
const vendorSettings = (opts.preset.vendor as VendorVsSettings)?.['microsoft.com/VisualStudioSettings/CMake/1.0'];
if (vendorSettings?.vsInstanceVersion) {
vendorVsVersion = vendorSettings.vsInstanceVersion;
log.info(localize('using.vendor.vs.version',
"Configure preset {0}: Using Visual Studio major version {1} from vendor settings.",
opts.preset.name, vendorVsVersion));
}
}
// If VS instance wasn't chosen using CMAKE_GENERATOR_INSTANCE, look up a matching instance
// that supports the specified toolset.
if (!vsInstall) {
// sort VS installs in order of descending version. This ensures we choose the latest supported install first.
vsInstalls.sort((a, b) => {
if (a.isPrerelease && !b.isPrerelease) {
return 1;
} else if (!a.isPrerelease && b.isPrerelease) {
return -1;
}
return -compareVersions(a.installationVersion, b.installationVersion);
});
for (const vs of vsInstalls) {
// Check for existence of vcvars script to determine whether desired host/target architecture is supported.
// toolset.host will be set by getToolset.
if (await getVcVarsBatScript(vs, toolset.host!, arch)) {
// If a toolset version is specified then check to make sure this vs instance has it installed.
if (toolset.version) {
const availableToolsets = await enumerateMsvcToolsets(vs.installationPath, vs.installationVersion);
// forcing non-null due to false positive (toolset.version is checked in conditional)
if (availableToolsets?.find(t => t.startsWith(toolset.version!))) {
vsInstall = vs;
break;
}
} else if (vendorVsVersion) {
// If a VS major version is specified via vendor settings, match against it.
if (vs.installationVersion.startsWith(vendorVsVersion.toString())) {
vsInstall = vs;
break;
}
} else if (!vsGeneratorVersion || vs.installationVersion.startsWith(vsGeneratorVersion.toString())) {
// If no toolset version specified then choose the latest VS instance for the given generator
vsInstall = vs;
break;
}
}
}
}
if (!vsInstall) {
if (opts.compilerName) {
log.error(localize('specified.cl.not.found',
"Configure preset {0}: Compiler {1} with toolset {2} and architecture {3} was not found, you may need to run the 'CMake: Scan for Compilers' command if this toolset exists on your computer.",
opts.preset.name, `"${opts.compilerName}.exe"`, toolset.version ? `"${toolset.version},${toolset.host}"` : `"${toolset.host}"`, `"${arch}"`));
} else {
log.error(localize('vs.not.found', "Configure preset {0}: No Visual Studio installation found that supports the specified toolset {1} and architecture {2}, you may need to run the 'CMake: Scan for Compilers' command if this toolset exists on your computer.",
opts.preset.name, toolset.version ? `"${toolset.version},${toolset.host}"` : `"${toolset.host}"`, `"${arch}"`));
}
} else {
log.info(localize('using.vs.instance', "Using developer environment from Visual Studio (instance {0}, version {1}, installed at {2})", vsInstall.instanceId, vsInstall.installationVersion, `"${vsInstall.installationPath}"`));
const vsEnv = await varsForVSInstallation(vsInstall, toolset.host!, arch, toolset.version);
const compilerEnv = vsEnv ?? EnvironmentUtils.create();
if (opts.shouldInterrogateForNinja) {
const vsCMakePaths = await paths.vsCMakePaths(vsInstall.instanceId);
if (vsCMakePaths.ninja) {
log.warning(localize('ninja.not.set', 'Ninja is not set on PATH, trying to use {0}', vsCMakePaths.ninja));
compilerEnv['PATH'] = `${path.dirname(vsCMakePaths.ninja)};${compilerEnv['PATH']}`;
}
}
return compilerEnv;
}
}
export function getVsDevEnvAutoDetectionInfo(preset: ConfigurePreset): VsDevEnvAutoDetectionInfo {
const cxxCompilerValue = getStringValueFromCacheVar(preset.cacheVariables?.['CMAKE_CXX_COMPILER']);
const cCompilerValue = getStringValueFromCacheVar(preset.cacheVariables?.['CMAKE_C_COMPILER']);
const cxxCompiler = cxxCompilerValue?.toLowerCase();
const cCompiler = cCompilerValue?.toLowerCase();
const explicitCompilerName = util.isSupportedCompiler(cxxCompiler) || util.isSupportedCompiler(cCompiler);
const hasExplicitCompiler = cxxCompilerValue !== null || cCompilerValue !== null;
const generatorIsNinja = preset.generator?.toLowerCase().includes("ninja") ?? false;