-
Notifications
You must be signed in to change notification settings - Fork 526
Expand file tree
/
Copy pathcmakeDriver.ts
More file actions
2318 lines (2094 loc) · 101 KB
/
cmakeDriver.ts
File metadata and controls
2318 lines (2094 loc) · 101 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
/**
* Defines base class for CMake drivers
*/ /** */
import * as path from 'path';
import * as vscode from 'vscode';
import * as lodash from "lodash";
import { CMakeExecutable } from '@cmt/cmakeExecutable';
import * as codepages from '@cmt/codePageTable';
import { ConfigureCancelInformation, ConfigureTrigger, DiagnosticsConfiguration } from "@cmt/cmakeProject";
import { CompileCommand } from '@cmt/compilationDatabase';
import { ConfigurationReader, checkBuildOverridesPresent, checkConfigureOverridesPresent, checkTestOverridesPresent, checkPackageOverridesPresent, defaultNumJobs } from '@cmt/config';
import { CMakeBuildConsumer, CompileOutputConsumer } from '@cmt/diagnostics/build';
import { CMakeOutputConsumer } from '@cmt/diagnostics/cmake';
import { RawDiagnosticParser } from '@cmt/diagnostics/util';
import { ProgressMessage } from '@cmt/drivers/drivers';
import * as expand from '@cmt/expand';
import { CMakeGenerator, effectiveKitEnvironment, Kit, kitChangeNeedsClean, KitDetect, getKitDetect, getVSKitEnvironment, getVsKitPreferredGenerator } from '@cmt/kits/kit';
import * as logging from '@cmt/logging';
import paths from '@cmt/paths';
import { fs } from '@cmt/pr';
import * as proc from '@cmt/proc';
import rollbar from '@cmt/rollbar';
import * as telemetry from '@cmt/telemetry';
import * as util from '@cmt/util';
import { ConfigureArguments, VariantOption } from '@cmt/kits/variant';
import * as nls from 'vscode-nls';
import { majorVersionSemver, minorVersionSemver, parseTargetTriple, TargetTriple } from '@cmt/triple';
import * as preset from '@cmt/presets/preset';
import * as codeModel from '@cmt/drivers/codeModel';
import { Environment, EnvironmentUtils } from '@cmt/environmentVariables';
import { CMakeTask, CMakeTaskProvider, CustomBuildTaskTerminal } from '@cmt/cmakeTaskProvider';
import { getValue } from '@cmt/presets/preset';
import { CacheEntry, CMakeCache } from '@cmt/cache';
import { CMakeBuildRunner } from '@cmt/cmakeBuildRunner';
import { DebuggerInformation } from '@cmt/debug/cmakeDebugger/debuggerConfigureDriver';
import { onBuildSettingsChange, onTestSettingsChange, onPackageSettingsChange } from '@cmt/ui/util';
import { CodeModelKind } from '@cmt/drivers/cmakeFileApi';
import { CommandResult } from 'vscode-cmake-tools';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
const log = logging.createLogger('driver');
export class NoGeneratorError extends Error {
message: string = localize('no.usable.generator.found', 'No usable generator found.');
}
export enum CMakePreconditionProblems {
ConfigureIsAlreadyRunning,
BuildIsAlreadyRunning,
NoSourceDirectoryFound,
MissingCMakeListsFile
}
interface CompilerInfo {
name: string;
version: string;
}
export enum ConfigureResultType {
NormalOperation,
ForcedCancel,
ConfigureInProgress,
BuildInProgress,
NoCache,
NoConfigurePreset,
Other
}
export interface ConfigureResult extends CommandResult {
resultType: ConfigureResultType;
}
export type CMakePreconditionProblemSolver = (e: CMakePreconditionProblems, config?: ConfigurationReader) => Promise<boolean>;
function nullableValueToString(arg: any | null | undefined): string {
return arg === null ? 'empty' : arg;
}
/**
* Description of an executable CMake target, defined via `add_executable()`.
*/
export interface ExecutableTarget {
/**
* The name of the target.
*/
name: string;
/**
* The absolute path to the build output.
*/
path: string;
/**
* The install locations of the target.
*/
isInstallTarget?: boolean;
/**
* The working directory for the debugger, from the DEBUGGER_WORKING_DIRECTORY target property.
*/
debuggerWorkingDirectory?: string;
}
/**
* A target with a name, but no output. Only used for targets that have a
* folder property.
*/
export interface FolderTarget {
type: 'folder';
name: string;
}
/**
* A target with a name, but no output. This may be created via `add_custom_command()`.
*/
export interface NamedTarget {
type: 'named';
name: string;
}
/**
* A target with a name, path, type and folder.
*/
export interface RichTarget {
type: 'rich';
name: string;
filepath: string;
targetType: string;
folder?: CodeModelKind.TargetObject;
installPaths?: InstallPath[];
debuggerWorkingDirectory?: string;
}
export type Target = NamedTarget | RichTarget;
export interface InstallPath {
path: string;
subPath: string;
}
/**
* Base class for CMake drivers.
*
* CMake drivers are separated because different CMake version warrant different
* communication methods. Older CMake versions need to be driven by the command
* line, but newer versions may be controlled via CMake server, which provides
* a much richer interface.
*
* This class defines the basis for what a driver must implement to work.
*/
/**
* Compare a new generator name against a cached CMAKE_GENERATOR value.
* Returns true when both are defined and differ (i.e. a mismatch that needs cleaning).
* Pure function — no I/O — exported for direct unit testing.
*/
export function generatorMismatch(newGeneratorName: string | undefined, cachedGeneratorValue: string | undefined): boolean {
if (!newGeneratorName || !cachedGeneratorValue) {
return false;
}
return cachedGeneratorValue !== newGeneratorName;
}
export abstract class CMakeDriver implements vscode.Disposable {
/**
* Do the configuration process for the current project.
*
* @returns The exit code from CMake
*/
protected abstract doConfigure(extra_args: string[], trigger?: ConfigureTrigger, consumer?: proc.OutputConsumer, showCommandOnly?: boolean, defaultConfigurePresetName?: string, configurePreset?: preset.ConfigurePreset | null, options?: proc.ExecutionOptions, debuggerInformation?: DebuggerInformation): Promise<number>;
protected abstract doCacheConfigure(): Promise<number>;
private _isConfiguredAtLeastOnce = false;
protected get isConfiguredAtLeastOnce(): boolean {
return this._isConfiguredAtLeastOnce;
}
protected _needsReconfigure = true;
/**
* Check if we need to reconfigure, such as if an important file has changed
*/
public async checkNeedsReconfigure(): Promise<boolean> {
return this._needsReconfigure;
}
protected async doPreCleanConfigure(): Promise<void> {
return Promise.resolve();
}
protected doPreBuild(): Promise<boolean> {
return Promise.resolve(true);
}
protected doPostBuild(): Promise<boolean> {
return Promise.resolve(true);
}
/**
* Check if using cached configuration is supported.
*/
protected abstract get isCacheConfigSupported(): boolean;
/**
* Event registration for code model updates
*
* This event is fired after update of the code model, like after cmake configuration.
*/
abstract onCodeModelChanged: vscode.Event<codeModel.CodeModelContent | null>;
/**
* List of targets known to CMake
*/
abstract get targets(): Target[];
abstract get codeModelContent(): codeModel.CodeModelContent | null;
/**
* List of executable targets known to CMake
*/
abstract get executableTargets(): ExecutableTarget[];
/**
* List of unique targets known to CMake
*/
abstract get uniqueTargets(): Target[];
/**
* List of all files (CMakeLists.txt and included .cmake files) used by CMake
* during configuration
*/
abstract get cmakeFiles(): string[];
/**
* Do any necessary disposal for the driver. For the CMake Server driver,
* this entails shutting down the server process and closing the open pipes.
*
* The reason this is separate from the regular `dispose()` is so that the
* driver shutdown may be `await`ed on to ensure full shutdown.
*/
abstract asyncDispose(): Promise<void>;
/**
* Construct the driver. Concrete instances should provide their own creation
* routines.
*/
protected constructor(public cmake: CMakeExecutable,
readonly config: ConfigurationReader,
protected sourceDirUnexpanded: string, // The un-expanded original source directory path, where the CMakeLists.txt exists.
private readonly isMultiProject: boolean,
private readonly __workspaceFolder: string,
readonly preconditionHandler: CMakePreconditionProblemSolver,
private readonly usingFileApi: boolean = false
) {
this.sourceDir = this.sourceDirUnexpanded;
}
/**
* The source directory, where the root CMakeLists.txt lives.
*
* @note This is distinct from the config values, since we do variable
* substitution.
*/
protected __sourceDir = '';
get sourceDir(): string {
return this.__sourceDir;
}
protected set sourceDir(value: string) {
this.__sourceDir = value;
}
/**
* Dispose the driver. This disposes some things synchronously, but also
* calls the `asyncDispose()` method to start any asynchronous shutdown.
*/
dispose() {
log.debug(localize('disposing.base.cmakedriver', 'Disposing base CMakeDriver'));
for (const sub of [this._settingsSub, this._argsSub, this._envSub, this._buildArgsSub, this._buildEnvSub, this._testArgsSub, this._testEnvSub, this._packEnvSub, this._packArgsSub, this._generalEnvSub]) {
sub.dispose();
}
rollbar.invokeAsync(localize('async.disposing.cmake.driver', 'Async disposing CMake driver'), () => this.asyncDispose());
}
/**
* The environment variables required by the current kit
*/
private _kitEnvironmentVariables = EnvironmentUtils.create();
/**
* Compute the environment variables that apply with substitutions by expansionOptions
*/
async computeExpandedEnvironment(toExpand: Environment, expanded: Environment): Promise<Environment> {
const env = EnvironmentUtils.create();
const opts = this.expansionOptions;
for (const entry of Object.entries(toExpand)) {
env[entry[0]] = await expand.expandString(entry[1], { ...opts, envOverride: expanded });
}
return env;
}
/**
* Get the environment variables that should be set at CMake-configure time.
*/
async getConfigureEnvironment(configurePreset?: preset.ConfigurePreset | null, extraEnvironmentVariables?: Environment): Promise<Environment> {
let envs;
if (this.useCMakePresets) {
envs = EnvironmentUtils.create(configurePreset ? configurePreset.environment : this._configurePreset?.environment);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.environment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.configureEnvironment, envs)]);
} else {
envs = this._kitEnvironmentVariables;
/* NOTE: By mergeEnvironment one by one to enable expanding self containd variable such as PATH properly */
/* If configureEnvironment and environment both configured different PATH, doing this will preserve them all */
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.environment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.configureEnvironment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this._variantEnv, envs)]);
}
if (extraEnvironmentVariables) {
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(extraEnvironmentVariables, envs)]);
}
return envs;
}
/**
* Get the environment variables that should be set at CMake-build time.
*/
async getCMakeBuildCommandEnvironment(in_env?: Environment): Promise<Environment> {
if (this.useCMakePresets) {
let envs = EnvironmentUtils.merge([in_env, this._buildPreset?.environment]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.environment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.buildEnvironment, envs)]);
return envs;
} else {
let envs = EnvironmentUtils.merge([in_env, this._kitEnvironmentVariables]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.environment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.buildEnvironment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this._variantEnv, envs)]);
return envs;
}
}
/**
* Get the environment variables that should be set at CTest and running program time.
*/
async getCTestCommandEnvironment(): Promise<Environment> {
if (this.useCMakePresets) {
let envs = EnvironmentUtils.create(this._testPreset?.environment);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.environment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.testEnvironment, envs)]);
if (this.useCMakePresets && this.testPreset !== null && checkTestOverridesPresent(this.config)) {
log.info(localize('test.with.overrides', 'NOTE: You are testing with preset {0}, but there are some overrides being applied from your VS Code settings.', this.testPreset.displayName ?? this.testPreset.name));
}
return envs;
} else {
let envs = this._kitEnvironmentVariables;
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.environment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.testEnvironment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this._variantEnv, envs)]);
return envs;
}
}
/**
* Get the environment variables that should be set at CPack and packaging time.
*/
async getCPackCommandEnvironment(): Promise<Environment> {
if (this.useCMakePresets) {
let envs = EnvironmentUtils.create(this._packagePreset?.environment);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.environment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.cpackEnvironment, envs)]);
if (this.useCMakePresets && this.packagePreset !== null && checkPackageOverridesPresent(this.config)) {
log.info(localize('package.with.overrides', 'NOTE: You are packaging with preset {0}, but there are some overrides being applied from your VS Code settings.', this.packagePreset.displayName ?? this.packagePreset.name));
}
return envs;
} else {
let envs = this._kitEnvironmentVariables;
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.environment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this.config.cpackEnvironment, envs)]);
envs = EnvironmentUtils.merge([envs, await this.computeExpandedEnvironment(this._variantEnv, envs)]);
return envs;
}
}
get onProgress(): vscode.Event<ProgressMessage> {
return (_cb: (ev: ProgressMessage) => any) => new util.DummyDisposable();
}
/**
* The current Kit. Starts out `null`, but once set, is never `null` again.
* We do some separation here to protect ourselves: The `_baseKit` property
* is `private`, so derived classes cannot change it, except via
* `_setBaseKit`, which only allows non-null kits. This prevents the derived
* classes from resetting the kit back to `null`.
*/
private _kit: Kit | null = null;
get kit(): Kit | null {
return this._kit;
}
private _kitDetect: KitDetect | null = null;
private _useCMakePresets: boolean = true;
get useCMakePresets(): boolean {
return this._useCMakePresets;
}
get configurePresetArchitecture(): string | preset.ValueStrategy | undefined {
return this._configurePreset?.architecture;
}
get configurePresetToolset(): string | preset.ValueStrategy | undefined {
return this._configurePreset?.toolset;
}
private _configurePreset: preset.ConfigurePreset | null = null;
private _buildPreset: preset.BuildPreset | null = null;
private _testPreset: preset.TestPreset | null = null;
get testPreset(): preset.TestPreset | null {
return this._testPreset;
}
private _packagePreset: preset.PackagePreset | null = null;
get packagePreset(): preset.PackagePreset | null {
return this._packagePreset;
}
private _workflowPreset: preset.WorkflowPreset | null = null;
get workflowPreset(): preset.WorkflowPreset | null {
return this._workflowPreset;
}
/**
* Get the vscode root workspace folder.
*
* @returns Returns the vscode root workspace folder. Returns `null` if no folder is open or the folder uri is not a
* `file://` scheme.
*/
get workspaceFolder() {
return this.__workspaceFolder;
}
protected variantKeywordSettings: Map<string, string> | null = null;
/**
* The options that will be passed to `expand.expandString` for this driver.
*/
get expansionOptions(): expand.ExpansionOptions {
const ws_root = util.lightNormalizePath(this.workspaceFolder || '.');
const target: Partial<TargetTriple> = parseTargetTriple(this._kitDetect?.triple ?? '') ?? {};
const version = this._kitDetect?.version ?? '0.0';
// Fill in default replacements
const vars: expand.KitContextVars = {
buildKit: this._kit ? this._kit.name : '__unknownkit__',
buildType: this.currentBuildType,
generator: this.generatorName || 'null',
workspaceFolder: ws_root,
workspaceFolderBasename: path.basename(ws_root),
workspaceHash: util.makeHashString(ws_root),
workspaceRoot: ws_root,
workspaceRootFolderName: path.basename(ws_root),
userHome: paths.userHome,
buildKitVendor: this._kitDetect?.vendor ?? '__unknown_vendor__',
buildKitTriple: this._kitDetect?.triple ?? '__unknown_triple__',
buildKitVersion: version,
buildKitHostOs: process.platform,
buildKitTargetOs: target.targetOs ?? '__unknown_target_os__',
buildKitTargetArch: target.targetArch ?? '__unknown_target_arch__',
buildKitVersionMajor: majorVersionSemver(version),
buildKitVersionMinor: minorVersionSemver(version),
sourceDir: this.sourceDir,
// DEPRECATED EXPANSION: Remove this in the future:
projectName: 'ProjectName'
};
// Update Variant replacements
const variantVars: { [key: string]: string } = {};
if (this.variantKeywordSettings) {
// allows to expansion of variant option keyword and replace it by the variant option short name
this.variantKeywordSettings.forEach((value: string, key: string) => variantVars[key] = value);
}
return { vars, variantVars };
}
static sourceDirExpansionOptions(workspaceFolderFspath: string | null): expand.ExpansionOptions {
const ws_root = util.lightNormalizePath(workspaceFolderFspath || '.');
// Fill in default replacements
const vars: expand.MinimalPresetContextVars = {
generator: 'generator',
workspaceFolder: ws_root,
workspaceFolderBasename: path.basename(ws_root),
sourceDir: '${sourceDir}',
workspaceHash: util.makeHashString(ws_root),
workspaceRoot: ws_root,
workspaceRootFolderName: path.basename(ws_root),
userHome: paths.userHome
};
return { vars };
}
getEffectiveSubprocessEnvironment(opts?: proc.ExecutionOptions): Environment {
const cur_env = process.env;
const kit_env = (this.config.ignoreKitEnv) ? EnvironmentUtils.create() : this._kitEnvironmentVariables;
const cmakeToolsEnv = EnvironmentUtils.create({ VSCODE_CMAKE_TOOLS: "1" });
return EnvironmentUtils.merge([cur_env, kit_env, cmakeToolsEnv, opts?.environment]);
}
executeCommand(command: string, args?: string[], consumer?: proc.OutputConsumer, options?: proc.ExecutionOptions): proc.Subprocess {
const environment = this.getEffectiveSubprocessEnvironment(options);
// On Windows, command-type-specific detection (e.g. .cmd → cmd, .ps1 → powershell)
// must take precedence over config.shell to avoid routing commands through
// an incompatible shell (e.g. .cmd files through Git Bash).
const commandShell = process.platform === 'win32' ? proc.determineShell(command) : false;
const shell = options?.shell ?? (commandShell || undefined) ?? this.config.shell ?? undefined;
const exec_options = { ...options, environment, shell };
return proc.execute(command, args, consumer, exec_options);
}
/**
* Launch the given compilation command in an embedded terminal.
* @param cmd The compilation command from a compilation database to run
*/
async runCompileCommand(cmd: CompileCommand): Promise<vscode.Terminal> {
const env = await this.getCMakeBuildCommandEnvironment();
if (this.useCMakePresets && this._buildPreset && checkBuildOverridesPresent(this.config)) {
log.info(localize('compile.with.overrides',
'NOTE: You are compiling with preset {0}, but there are some overrides being applied from your VS Code settings.',
this._buildPreset.displayName ?? this._buildPreset.name));
}
const args = cmd.arguments;
if (!args || args.length === 0) {
// Fallback: no structured args available — send the raw command string via terminal.
// This path should never be reached because CompilationDatabase always populates arguments.
const term = vscode.window.createTerminal({
name: localize('file.compilation', 'File Compilation'),
cwd: cmd.directory,
env
});
term.show();
term.sendText(cmd.command, true);
return term;
}
// Spawn the compiler directly via proc.execute() to avoid the PTY 4096-byte
// input-buffer truncation bug (https://github.com/microsoft/vscode-cmake-tools/issues/4836).
// We open a Pseudoterminal so output appears in the Terminal panel without any
// shell intermediary — args are passed as an array straight to child_process.spawn.
const writeEmitter = new vscode.EventEmitter<string>();
const closeEmitter = new vscode.EventEmitter<number>();
let activeProcess: proc.Subprocess | undefined;
let processExitCode: number | undefined;
const pty: vscode.Pseudoterminal = {
onDidWrite: writeEmitter.event,
onDidClose: closeEmitter.event,
open: () => {
const executable = args[0];
const execArgs = args.slice(1);
writeEmitter.fire(proc.buildCmdStr(executable, execArgs) + '\r\n');
activeProcess = proc.execute(executable, execArgs, {
output: (line: string) => writeEmitter.fire(line + '\r\n'),
error: (line: string) => writeEmitter.fire(line + '\r\n')
}, { cwd: cmd.directory, environment: env });
activeProcess.result.then(result => {
activeProcess = undefined;
const retc = result.retc ?? 0;
processExitCode = retc;
if (retc !== 0) {
writeEmitter.fire(localize('compile.finished.with.error',
'Compilation finished with error(s).') + '\r\n');
} else {
writeEmitter.fire(localize('compile.finished.successfully',
'Compilation finished successfully.') + '\r\n');
}
// Keep terminal open so user can see the output. Only close when
// user presses a key or closes the terminal manually.
// See https://github.com/microsoft/vscode-cmake-tools/issues/4896
writeEmitter.fire(localize('press.any.key.to.close',
'Press any key to close the terminal...') + '\r\n');
}, (e: any) => {
activeProcess = undefined;
// Use positive exit code per VS Code PTY API convention
processExitCode = 1;
writeEmitter.fire((e?.message ?? String(e)) + '\r\n');
writeEmitter.fire(localize('press.any.key.to.close',
'Press any key to close the terminal...') + '\r\n');
});
},
close: () => {
// Terminate the compiler process if the user closes the terminal
// while compilation is still running, to avoid orphaned processes.
if (activeProcess?.child) {
void util.termProc(activeProcess.child);
activeProcess = undefined;
}
},
handleInput: (_data: string) => {
// Close the terminal when the user presses any key after the
// process has finished. If the process is still running, ignore input.
if (processExitCode !== undefined) {
closeEmitter.fire(processExitCode);
}
}
};
const term = vscode.window.createTerminal({
name: localize('file.compilation', 'File Compilation'),
pty
});
term.show();
return term;
}
/**
* Remove the prior CMake configuration files.
*/
protected async _cleanPriorConfiguration() {
const build_dir = this.binaryDir;
const cache = this.cachePath;
const cmake_files = this.config.deleteBuildDirOnCleanConfigure ? build_dir : path.join(build_dir, 'CMakeFiles');
if (await fs.exists(cache)) {
log.info(localize('removing', 'Removing {0}', encodeURI(cache)));
try {
await fs.unlink(cache);
} catch {
log.error(localize('unlink.failed', 'Failed to remove cache file {0}', this.cachePath));
}
}
if (await fs.exists(cmake_files)) {
log.info(localize('removing', 'Removing {0}', encodeURI(cmake_files)));
await fs.rmdir(cmake_files);
}
}
/**
* Check if the generator to be used differs from what is cached in CMakeCache.txt.
*/
protected async _hasGeneratorChanged(newGeneratorName: string | undefined): Promise<boolean> {
if (!newGeneratorName) {
return false;
}
const cachePath = this.cachePath;
if (!await fs.exists(cachePath)) {
return false;
}
const cache = await CMakeCache.fromPath(cachePath);
const cachedGenerator = cache.get('CMAKE_GENERATOR');
if (generatorMismatch(newGeneratorName, cachedGenerator?.value)) {
log.info(localize('generator.changed', 'Generator changed from {0} to {1}; cleaning prior configuration', cachedGenerator!.value, newGeneratorName));
return true;
}
return false;
}
/**
* Remove the entire build directory.
*/
protected async _cleanBuildDirectory() {
const build_dir = this.binaryDir;
if (await fs.exists(build_dir)) {
log.info(localize('removing', 'Removing {0}', encodeURI(build_dir)));
await fs.rmdir(build_dir);
}
}
/**
* Change the current configure preset. This lets the driver reload, if necessary.
* @param configurePreset The new configure preset
*/
async setConfigurePreset(configurePreset: preset.ConfigurePreset | null): Promise<void> {
if (configurePreset) {
log.info(localize('switching.to.config.preset', 'Switching to configure preset: {0}', configurePreset.name));
// Skip the full doSetConfigurePreset (which unconditionally sets
// _needsReconfigure = true) when the expanded preset hasn't changed
// and the CMake cache still exists on disk.
// This avoids unnecessary reconfigures when reapplyPresets() is called
// but preset files on disk are identical (see #4502).
if (this._configurePreset && lodash.isEqual(configurePreset, this._configurePreset) && await fs.exists(this.cachePath)) {
return;
}
const newBinaryDir = configurePreset.binaryDir;
const needs_clean = this.binaryDir === newBinaryDir && preset.configurePresetChangeNeedsClean(configurePreset, this._configurePreset);
await this.doSetConfigurePreset(needs_clean, async () => {
await this._setConfigurePreset(configurePreset);
});
} else {
log.info(localize('unsetting.config.preset', 'Unsetting configure preset'));
await this.doSetConfigurePreset(false, async () => {
await this._setConfigurePreset(configurePreset);
});
}
}
private async _setConfigurePreset(configurePreset: preset.ConfigurePreset | null): Promise<void> {
this._configurePreset = configurePreset;
log.debug(localize('cmakedriver.config.preset.set.to', 'CMakeDriver configure preset set to {0}', configurePreset?.name || null));
this._binaryDir = configurePreset?.binaryDir || '';
if (configurePreset) {
if (configurePreset.generator) {
this._generator = {
name: configurePreset.generator,
platform: configurePreset.architecture ? getValue(configurePreset.architecture) : undefined,
toolset: configurePreset.toolset ? getValue(configurePreset.toolset) : undefined
};
} else {
log.debug(localize('no.generator', 'No generator specified'));
}
} else {
this._generator = null;
}
}
/**
* Change the current build preset
* @param buildPreset The new build preset
*/
async setBuildPreset(buildPreset: preset.BuildPreset | null): Promise<void> {
if (buildPreset) {
log.info(localize('switching.to.build.preset', 'Switching to build preset: {0}', buildPreset.name));
} else {
log.info(localize('unsetting.build.preset', 'Unsetting build preset'));
}
await this.doSetBuildPreset(async () => {
await this._setBuildPreset(buildPreset);
});
}
private async _setBuildPreset(buildPreset: preset.BuildPreset | null): Promise<void> {
this._buildPreset = buildPreset;
log.debug(localize('cmakedriver.build.preset.set.to', 'CMakeDriver build preset set to {0}', buildPreset?.name || null));
}
/**
* Change the current test preset
* @param testPreset The new test preset
*/
async setTestPreset(testPreset: preset.TestPreset | null): Promise<void> {
if (testPreset) {
log.info(localize('switching.to.test.preset', 'Switching to test preset: {0}', testPreset.name));
} else {
log.info(localize('unsetting.test.preset', 'Unsetting test preset'));
}
await this.doSetTestPreset(async () => {
await this._setTestPreset(testPreset);
});
}
private async _setTestPreset(testPreset: preset.TestPreset | null): Promise<void> {
this._testPreset = testPreset;
log.debug(localize('cmakedriver.test.preset.set.to', 'CMakeDriver test preset set to {0}', testPreset?.name || null));
}
/**
* Change the current package preset
* @param packagePreset The new package preset
*/
async setPackagePreset(packagePreset: preset.PackagePreset | null): Promise<void> {
if (packagePreset) {
log.info(localize('switching.to.package.preset', 'Switching to package preset: {0}', packagePreset.name));
} else {
log.info(localize('unsetting.package.preset', 'Unsetting package preset'));
}
await this.doSetPackagePreset(async () => {
await this._setPackagePreset(packagePreset);
});
}
private async _setPackagePreset(packagePreset: preset.PackagePreset | null): Promise<void> {
this._packagePreset = packagePreset;
log.debug(localize('cmakedriver.package.preset.set.to', 'CMakeDriver package preset set to {0}', packagePreset?.name || null));
}
/**
* Change the current workflow preset
* @param workflowPreset The new workflow preset
*/
async setWorkflowPreset(workflowPreset: preset.WorkflowPreset | null): Promise<void> {
if (workflowPreset) {
log.info(localize('switching.to.workflow.preset', 'Switching to workflow preset: {0}', workflowPreset.name));
} else {
log.info(localize('unsetting.workflow.preset', 'Unsetting workflow preset'));
}
await this.doSetWorkflowPreset(async () => {
await this._setWorkflowPreset(workflowPreset);
});
}
private async _setWorkflowPreset(workflowPreset: preset.WorkflowPreset | null): Promise<void> {
this._workflowPreset = workflowPreset;
log.debug(localize('cmakedriver.workflow.preset.set.to', 'CMakeDriver workflow preset set to {0}', workflowPreset?.name || null));
}
/**
* Ensure that variables are up to date (e.g. sourceDirectory, buildDirectory, env, installDirectory)
*/
async refreshSettings() {
await this._refreshExpansions();
}
/**
* Change the current kit. This lets the driver reload, if necessary.
* @param kit The new kit
*/
async setKit(kit: Kit, preferredGenerators: CMakeGenerator[]): Promise<void> {
if (this.useCMakePresets) {
log.info(localize('skip.set.kit', 'Using preset, skip setting kit: {0}', kit.name));
return;
}
let switch_to_kit_info = localize('switching.to.kit', 'Switching to kit: {0}', kit.name);
if (Array.isArray(kit.visualStudioArguments)) {
switch_to_kit_info += ` visualStudioArguments: ${JSON.stringify(kit.visualStudioArguments)}`;
}
log.info(switch_to_kit_info);
const oldBinaryDir = this.binaryDir;
const needsCleanIfKitChange = kitChangeNeedsClean(kit, this._kit);
await this.doSetKit(async () => {
await this._setKit(kit, preferredGenerators);
await this._refreshExpansions();
const scope = this.workspaceFolder ? vscode.Uri.file(this.workspaceFolder) : undefined;
const newBinaryDir = util.lightNormalizePath(await expand.expandString(this.config.buildDirectory(this.isMultiProject, scope), this.expansionOptions));
const generatorChanged = await this._hasGeneratorChanged(this._generator?.name);
if ((needsCleanIfKitChange || generatorChanged) && (newBinaryDir === oldBinaryDir)) {
await this._cleanPriorConfiguration();
}
});
}
private async _setKit(kit: Kit, preferredGenerators: CMakeGenerator[]): Promise<void> {
this._kit = Object.seal({ ...kit });
this._kitDetect = await getKitDetect(this._kit);
log.debug(localize('cmakedriver.kit.set.to', 'CMakeDriver Kit set to {0}', kit.name));
this._kitEnvironmentVariables = await effectiveKitEnvironment(kit, this.expansionOptions);
// Place a kit preferred generator at the front of the list.
if (kit.preferredGenerator) {
preferredGenerators.unshift(kit.preferredGenerator);
}
// If no preferred generator is defined by the current kit or the user settings,
// it's time to consider the defaults.
if (preferredGenerators.length === 0
&& !(this.usingFileApi
&& (this.cmake.version && util.versionGreaterOrEquals(this.cmake.version, this.cmake.minimalDefaultGeneratorVersion))
&& kit.name === "__unspec__")
) {
preferredGenerators.push({ name: "Ninja" });
preferredGenerators.push({ name: "Unix Makefiles" });
}
// For VS kits that don't have preferredGenerator (e.g., scanned before
// a VS version was added), derive the VS generator as a last-resort
// fallback so it is tried only after Ninja / Unix Makefiles.
if (!kit.preferredGenerator && kit.visualStudio) {
const derived = await getVsKitPreferredGenerator(kit);
if (derived) {
preferredGenerators.push(derived);
}
}
// Use the "best generator" logic only if the user did not define a particular
// generator to be used via the `cmake.generator` setting.
if (this.config.generator) {
this._generator = {
name: this.config.generator,
platform: this.config.platform || undefined,
toolset: this.config.toolset || undefined
};
} else {
this._generator = await this.findBestGenerator(preferredGenerators);
}
}
protected abstract doSetConfigurePreset(needsClean: boolean, cb: () => Promise<void>): Promise<void>;
protected abstract doSetBuildPreset(cb: () => Promise<void>): Promise<void>;
protected abstract doSetTestPreset(cb: () => Promise<void>): Promise<void>;
protected abstract doSetPackagePreset(cb: () => Promise<void>): Promise<void>;
protected abstract doSetWorkflowPreset(cb: () => Promise<void>): Promise<void>;
protected abstract doSetKit(cb: () => Promise<void>): Promise<void>;
protected get generator(): CMakeGenerator | null {
return this._generator;
}
protected _generator: CMakeGenerator | null = null;
/**
* The CMAKE_BUILD_TYPE to use
*/
private _variantBuildType: string = 'Debug';
/**
* The arguments to pass to CMake during a configuration according to the current variant
*/
private _variantConfigureSettings: ConfigureArguments = {};
/**
* Determine if we set BUILD_SHARED_LIBS to TRUE or FALSE
*/
private _variantLinkage: ('static' | 'shared' | null) = null;
/**
* Environment variables defined by the current variant
*/
private _variantEnv: Environment = EnvironmentUtils.create();
/**
* Change the current options from the variant.
* @param opts The new options
* @param keywordSetting Variant Keywords for identification of a variant option
*/
async setVariant(opts: VariantOption, keywordSetting: Map<string, string> | null) {
log.debug(localize('setting.new.variant', 'Setting new variant {0}', opts.short || '(Unnamed)'));
this._variantBuildType = opts.buildType || this._variantBuildType;
this._variantConfigureSettings = opts.settings || this._variantConfigureSettings;
this._variantLinkage = opts.linkage || null;
this._variantEnv = EnvironmentUtils.create(opts.env);
this.variantKeywordSettings = keywordSetting || null;
await this._refreshExpansions();
}
protected doRefreshExpansions(cb: () => Promise<void>): Promise<void> {
return cb();
}
private async _refreshExpansions(configurePreset?: preset.ConfigurePreset | null) {
return this.doRefreshExpansions(async () => {
this.sourceDir = await util.normalizeAndVerifySourceDir(this.sourceDirUnexpanded, CMakeDriver.sourceDirExpansionOptions(this.workspaceFolder));
const opts = this.expansionOptions;
opts.envOverride = await this.getConfigureEnvironment(configurePreset);
const installPrefix = this.config.installPrefix;
if (installPrefix) {
this._installDir = util.lightNormalizePath(await expand.expandString(installPrefix, opts));
}
if (!this.useCMakePresets) {
const scope = this.workspaceFolder ? vscode.Uri.file(this.workspaceFolder) : undefined;
this._binaryDir = util.lightNormalizePath(await expand.expandString(this.config.buildDirectory(this.isMultiProject, scope), opts));
}
});
}
/**
* Path to where the root CMakeLists.txt file should be
*/
get mainListFile(): string {
const file = path.join(this.sourceDir, 'CMakeLists.txt');
return util.lightNormalizePath(file);
}
/**
* Directory where build output is stored.
*/
get binaryDir(): string {
return this._binaryDir;
}
private _binaryDir = '';
/**
* Directory where the targets will be installed.
*/
private get installDir(): string | null {
return this._installDir;
}
private _installDir: string | null = null;
/**
* @brief Get the path to the CMakeCache file in the build directory
*/
get cachePath(): string {
// TODO: Cache path can change if build dir changes at runtime