-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathmake.ts
2533 lines (2301 loc) · 84.7 KB
/
make.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
// Support for make operations
import * as configuration from "./configuration";
import * as cpp from "vscode-cpptools";
import * as cpptools from "./cpptools";
import { extension } from "./extension";
import * as fs from "fs";
import * as logger from "./logger";
import * as parser from "./parser";
import * as path from "path";
import * as util from "./util";
import * as telemetry from "./telemetry";
import * as vscode from "vscode";
import { v4 as uuidv4 } from "uuid";
import * as nls from "vscode-nls";
nls.config({
messageFormat: nls.MessageFormat.bundle,
bundleFormat: nls.BundleFormat.standalone,
})();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
const recursiveString = localize("recursive", "(recursive)");
let isBuilding: boolean = false;
export function getIsBuilding(): boolean {
return isBuilding;
}
export function setIsBuilding(building: boolean): void {
isBuilding = building;
}
let isConfiguring: boolean = false;
export function getIsConfiguring(): boolean {
return isConfiguring;
}
export function setIsConfiguring(configuring: boolean): void {
isConfiguring = configuring;
}
let configureIsInBackground: boolean = false;
export function getConfigureIsInBackground(): boolean {
return configureIsInBackground;
}
export function setConfigureIsInBackground(background: boolean): void {
configureIsInBackground = background;
}
let configureIsClean: boolean = false;
export function getConfigureIsClean(): boolean {
return configureIsClean;
}
export function setConfigureIsClean(clean: boolean): void {
configureIsClean = clean;
}
let isPreConfiguring: boolean = false;
export function getIsPreConfiguring(): boolean {
return isPreConfiguring;
}
export function setIsPreConfiguring(preConfiguring: boolean): void {
isPreConfiguring = preConfiguring;
}
let isPostConfiguring: boolean = false;
export function getIsPostConfiguring(): boolean {
return isPostConfiguring;
}
export function setIsPostConfiguring(postConfiguring: boolean): void {
isPostConfiguring = postConfiguring;
}
// Leave positive error codes for make exit values
export enum ConfigureBuildReturnCodeTypes {
success = 0,
blocked = -1,
cancelled = -2,
notFound = -3,
outOfDate = -4,
other = -5,
saveFailed = -6,
fullFeatureFalse = -7,
untrusted = -8,
}
export enum Operations {
preConfigure = "pre-configure",
postConfigure = "post-configure",
configure = "configure",
build = "build",
changeConfiguration = "change makefile configuration",
changeBuildTarget = "change build target",
changeLaunchTarget = "change launch target",
debug = "debug",
run = "run",
}
export enum TriggeredBy {
buildTarget = "command pallette (buildTarget)",
buildCleanTarget = "command pallette (buildCleanTarget)",
buildAll = "command pallette (buildAll)",
buildCleanAll = "command pallette (buildCleanAll)",
preconfigure = "command pallette (preConfigure)",
alwaysPreconfigure = "settings (alwaysPreConfigure)",
postConfigure = "command pallette (postConfigure)",
alwaysPostConfigure = "settings (alwaysPostConfigure)",
configure = "command pallette (configure)",
configureOnOpen = "settings (configureOnOpen)",
cleanConfigureOnOpen = "configure dirty (on open), settings (configureOnOpen)",
cleanConfigure = "command pallette (clean configure)",
configureBeforeBuild = "configure dirty (before build), settings (configureAfterCommand)",
configureAfterConfigurationChange = "settings (configureAfterCommand), command pallette (setBuildConfiguration)",
configureAfterEditorFocusChange = "configure dirty (editor focus change), settings (configureOnEdit)",
configureBeforeTargetChange = "configure dirty (before target change), settings (configureAfterCommand)",
configureAfterTargetChange = "settings (configureAfterCommand), command pallette (setBuildTarget)",
configureBeforeLaunchTargetChange = "configureDirty (before launch target change), settings (configureAfterCommand)",
launch = "Launch (debug|run)",
tests = "Makefile Tools Regression Tests",
}
let fileIndex: Map<string, cpptools.SourceFileConfigurationItem> = new Map<
string,
cpptools.SourceFileConfigurationItem
>();
let workspaceBrowseConfiguration: cpp.WorkspaceBrowseConfiguration = {
browsePath: [],
};
export function getDeltaCustomConfigurationProvider(): cpptools.CustomConfigurationProvider {
let provider: cpptools.CustomConfigurationProvider = {
fileIndex: fileIndex,
workspaceBrowse: workspaceBrowseConfiguration,
};
return provider;
}
export function setCustomConfigurationProvider(
provider: cpptools.CustomConfigurationProvider
): void {
fileIndex = provider.fileIndex;
workspaceBrowseConfiguration = provider.workspaceBrowse;
}
// Identifies and logs whether an operation should be prevented from running.
// So far, the only blocking scenarios are if an ongoing configure, pre-configure or build
// is blocking other new similar operations and setter commands (selection of new configurations, targets, etc...)
// Getter commands are not blocked, even if by the time the (pre-)configure or build operations are completed
// they might be out of date.
// For the moment, the status bar buttons don't change when an operation is blocked
// and cancelling is done only via a button in the bottom right popup.
// Clicking the status bar buttons attempts to run the corresponding operation,
// which triggers a popup and returns early if it should be blocked. Same for pallette commands.
// In future we may enable/disable or change text depending on the blocking state.
export function blockedByOp(
op: Operations,
showPopup: boolean = true
): Operations | undefined {
let blocker: Operations | undefined;
if (getIsPreConfiguring()) {
blocker = Operations.preConfigure;
}
if (getIsPostConfiguring()) {
blocker = Operations.postConfigure;
}
if (getIsConfiguring()) {
// A configure in the background shouldn't block anything except another configure
if (getConfigureIsInBackground() && op !== Operations.configure) {
vscode.window.showInformationMessage(
localize(
"project.configuring.background.op.may.run.on.out.of.date.input",
"The project is configuring in the background and {0} may run on out-of-date input.",
op
)
);
} else {
blocker = Operations.configure;
}
}
if (getIsBuilding()) {
blocker = Operations.build;
}
if (blocker && showPopup) {
vscode.window.showErrorMessage(
localize(
"cannot.op.because.project.already.doing",
"Cannot {0} because the project is already doing a '{1}'.",
`'${op}'`,
blocker
)
);
}
return blocker;
}
async function saveAll(): Promise<boolean> {
if (configuration.getSaveBeforeBuildOrConfigure()) {
logger.message(
localize("saving.opened.files", "Saving opened files before build.")
);
let saveSuccess: boolean = await vscode.workspace.saveAll();
if (saveSuccess) {
return true;
} else {
logger.message(
localize("saved.opened.files.failed", "Saving opened files failed.")
);
let yesButton: string = localize("yes", "Yes");
let noButton: string = localize("no", "No");
const chosen: vscode.MessageItem | undefined =
await vscode.window.showErrorMessage<vscode.MessageItem>(
"Saving opened files failed. Do you want to continue anyway?",
{
title: yesButton,
isCloseAffordance: false,
},
{
title: noButton,
isCloseAffordance: true,
}
);
return chosen !== undefined && chosen.title === yesButton;
}
} else {
return true;
}
}
export function prepareBuildTarget(target: string): string[] {
let makeArgs: string[] = [];
// Prepend the target to the arguments given in the configurations json.
// If a clean build is desired, "clean" should precede the target.
if (target) {
makeArgs.push(target);
}
makeArgs = makeArgs.concat(configuration.getConfigurationMakeArgs());
logger.message(
localize(
"building.target.with.command",
"Building target \"{0}\" with command: '{1} {2}'",
target,
configuration.getConfigurationMakeCommand(),
makeArgs.join(" ")
)
);
return makeArgs;
}
// Build targets allow list for telemetry
function processTargetForTelemetry(target: string | undefined): string {
if (!target || target === "") {
return "(unset)";
} else if (target === "all" || target === "clean") {
return target;
}
return "..."; // private undisclosed info
}
// PID of the process that may be running currently.
// At any moment, there is either no process or only one process running
// (make for configure, make for build or pre-configure cmd/bash).
// TODO: improve the code regarding curPID and how util.spawnChildProcess is setting it in make.ts unit.
let curPID: number = -1;
export function getCurPID(): number {
return curPID;
}
export function setCurPID(pid: number): void {
curPID = pid;
}
const makefileBuildTaskName: string = "Makefile Tools Build Task";
export async function buildTarget(
triggeredBy: TriggeredBy,
target: string,
clean: boolean = false
): Promise<number> {
if (blockedByOp(Operations.build)) {
return ConfigureBuildReturnCodeTypes.blocked;
}
if (!saveAll()) {
return ConfigureBuildReturnCodeTypes.saveFailed;
}
// Same start time for build and an eventual configure.
let buildStartTime: number = Date.now();
// warn about an out of date configure state and configure if makefile.configureAfterCommand allows.
let configureExitCode: number | undefined; // used for telemetry
let configureElapsedTime: number | undefined; // used for telemetry
if (extension.getState().configureDirty) {
logger.message(
localize(
"project.needs.configure.for.build",
"The project needs to configure in order to build properly the current target."
)
);
if (configuration.getConfigureAfterCommand()) {
configureExitCode = await configure(TriggeredBy.configureBeforeBuild);
if (configureExitCode !== ConfigureBuildReturnCodeTypes.success) {
logger.message(
localize(
"running.build.after.configure.fail",
"Attempting to run build after a failed configure."
)
);
}
configureElapsedTime = util.elapsedTimeSince(buildStartTime);
}
}
// Prepare a notification popup
let config: string | undefined =
configuration.getCurrentMakefileConfiguration();
let configAndTarget: string = config;
if (target) {
target = target.trimLeft();
if (target !== "") {
configAndTarget += "/" + target;
}
}
configAndTarget = `"${configAndTarget}"`;
const cleanPopup: string = localize(
"make.clean.popup",
"Building clean the current makefile configuration {0}",
configAndTarget
);
const notCleanPopup: string = localize(
"make.not.clean.popup",
"Building the current makefile configuration {0}",
configAndTarget
);
let popupStr: string = clean ? cleanPopup : notCleanPopup;
let cancelBuild: boolean = false; // when the build was cancelled by the user
try {
return await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: popupStr,
cancellable: true,
},
async (progress, cancel) => {
cancel.onCancellationRequested(async () => {
progress.report({
increment: 1,
message: localize("make.build.cancelling", "Cancelling..."),
});
logger.message(
localize(
"user.cancelling.build",
"The user is cancelling the build..."
)
);
cancelBuild = true;
// Kill the task that is used for building.
// This will take care of all processes that were spawned.
let myTask: vscode.TaskExecution | undefined =
vscode.tasks.taskExecutions.find((tsk) => {
if (tsk.task.name === makefileBuildTaskName) {
return tsk;
}
});
logger.message(
localize(
"killing.task",
'Killing task "{0}".',
makefileBuildTaskName
)
);
myTask?.terminate();
});
setIsBuilding(true);
// If required by the "makefile.clearOutputBeforeBuild" setting,
// we need to clear the terminal output when "make"-ing target "clean"
// (but not when "make"-ing the following intended target, so that we see both together)
// or when "make"-ing the intended target in case of a not-clean build.
let clearOutput: boolean =
configuration.getClearOutputBeforeBuild() || false;
if (clean) {
// We don't need to track the return code for 'make "clean"'.
// We want to proceed with the 'make "target"' step anyway.
// The relevant return code for telemetry will be the second one.
// If the clean step fails, doBuildTarget will print an error message in the terminal.
await doBuildTarget(progress, "clean", clearOutput);
}
let retc: number = await doBuildTarget(
progress,
target,
clearOutput && !clean
);
// We need to know whether this build was cancelled by the user
// more than the real exit code of the make process in this circumstance.
if (cancelBuild) {
retc = ConfigureBuildReturnCodeTypes.cancelled;
}
let buildElapsedTime: number = util.elapsedTimeSince(buildStartTime);
const telemetryProperties: telemetry.Properties = {
exitCode: retc?.toString() || "undefined",
target: processTargetForTelemetry(target),
triggeredBy: triggeredBy,
};
const telemetryMeasures: telemetry.Measures = {
buildTotalElapsedTime: buildElapsedTime,
};
// Report if this build ran also a configure and how long it took.
if (configureExitCode !== undefined) {
telemetryProperties.configureExitCode = configureExitCode.toString();
}
if (configureElapsedTime !== undefined) {
telemetryMeasures.configureElapsedTime = configureElapsedTime;
}
telemetry.logEvent("build", telemetryProperties, telemetryMeasures);
cancelBuild = false;
return retc;
}
);
} finally {
setIsBuilding(false);
}
}
export async function doBuildTarget(
progress: vscode.Progress<{}>,
target: string,
clearTerminalOutput: boolean
): Promise<number> {
let makeArgs: string[] = prepareBuildTarget(target);
try {
const quotingStlye: vscode.ShellQuoting = vscode.ShellQuoting.Strong;
const quotingStyleName: string = "Strong";
let myTaskCommand: vscode.ShellQuotedString = {
value: configuration.getConfigurationMakeCommand(),
quoting: quotingStlye,
};
let myTaskArgs: vscode.ShellQuotedString[] = makeArgs.map((arg) => {
return { value: arg, quoting: quotingStlye };
});
const cwd: string = configuration.makeBaseDirectory();
if (!util.checkDirectoryExistsSync(cwd)) {
logger.message(
localize(
"target.failed.because.cwd.not.exists",
'Target "{0}" failed to build because CWD passed in does not exist ({1}).',
target,
cwd
)
);
return ConfigureBuildReturnCodeTypes.notFound;
}
let myTaskOptions: vscode.ShellExecutionOptions = {
// Only pass a defined environment if there are modified environment variables.
env:
Object.keys(util.modifiedEnvironmentVariables).length > 0
? util.mergeEnvironment(
util.modifiedEnvironmentVariables as util.EnvironmentVariables
)
: undefined,
cwd,
};
let shellExec: vscode.ShellExecution = new vscode.ShellExecution(
myTaskCommand,
myTaskArgs,
myTaskOptions
);
let myTask: vscode.Task = new vscode.Task(
{ type: "shell", group: "build", label: makefileBuildTaskName },
vscode.TaskScope.Workspace,
makefileBuildTaskName,
"makefile",
shellExec
);
myTask.problemMatchers = configuration.getConfigurationProblemMatchers();
myTask.presentationOptions.clear = clearTerminalOutput;
myTask.presentationOptions.showReuseMessage = true;
logger.message(
localize(
"executing.task.quoting.style",
'Executing task: "{0}" with quoting style "{1}"\n command name: {2}\n command args {3}',
myTask.name,
quotingStyleName,
myTaskCommand.value,
makeArgs.join()
),
"Debug"
);
await vscode.tasks.executeTask(myTask);
const result: number = await new Promise<number>((resolve) => {
let disposable: vscode.Disposable = vscode.tasks.onDidEndTaskProcess(
(e: vscode.TaskProcessEndEvent) => {
if (e.execution.task.name === makefileBuildTaskName) {
disposable.dispose();
resolve(e.exitCode ?? ConfigureBuildReturnCodeTypes.other);
}
}
);
});
if (result !== ConfigureBuildReturnCodeTypes.success) {
logger.message(
localize(
"target.failed.to.build",
'Target "{0}" failed to build.',
target
)
);
} else {
logger.message(
localize(
"target.build.successfully",
'Target "{0}" built successfully.',
target
)
);
}
return result;
} catch (error) {
// No need for notification popup, since the build result is visible already in the output channel
logger.message(error);
return ConfigureBuildReturnCodeTypes.notFound;
}
}
// Content to be parsed by various operations post configure (like finding all build/launch targets).
// Represents the content of the provided makefile.buildLog or a fresh output of make --dry-run
// (which is also written into makefile.configurationCachePath).
let parseContent: string | undefined;
export function getParseContent(): string | undefined {
return parseContent;
}
export function setParseContent(content: string): void {
parseContent = content;
}
// The source file of parseContent (build log or configuration dryrun cache).
let parseFile: string | undefined;
export function getParseFile(): string | undefined {
return parseFile;
}
export function setParseFile(file: string): void {
parseFile = file;
}
// Targets need to parse a dryrun make invocation that does not include a target name
// (other than default empty "" or the standard "all"), otherwise it would produce
// a subset of all the targets involved in the makefile (only the ones triggered
// by building the current target).
export async function generateParseContent(
progress: vscode.Progress<{}>,
cancel: vscode.CancellationToken,
forTargets: boolean = false,
recursive: boolean = false
): Promise<ConfigureSubphaseStatus> {
if (cancel.isCancellationRequested) {
return {
retc: ConfigureBuildReturnCodeTypes.cancelled,
elapsed: 0,
};
}
let startTime: number = Date.now();
// Rules for parse content and file:
// 1. makefile.buildLog provided by the user in settings
// 2. configuration cache (the previous dryrun output): makefile.configurationCachePath
// 3. the make dryrun output if (2) is missing
// We do not use buildLog for build targets analysis because
// we can afford to invoke make -pRrq (very quick even on large projects).
// We make sure to give the regression tests suite a build log that already contains
// targets information because we want to avoid invoking make for now.
let buildLog: string | undefined = configuration.getConfigurationBuildLog();
if (
buildLog &&
(!forTargets || process.env["MAKEFILE_TOOLS_TESTING"] === "1")
) {
parseContent = util.readFile(buildLog);
if (parseContent) {
parseFile = buildLog;
return {
retc: ConfigureBuildReturnCodeTypes.success,
elapsed: util.elapsedTimeSince(startTime),
};
}
}
const dryRunString = localize(
"make.generating.dryrun",
"Generating dry-run output"
);
const forTargetsString = localize(
"make.generating.forTargets",
"(for targets specifically)"
);
progress.report({
increment: 1,
message:
dryRunString +
(recursive ? ` ${recursiveString}` : "") +
(forTargets ? ` ${forTargetsString}` : "" + "..."),
});
// Continue with the make dryrun invocation
let makeArgs: string[] = [];
// Prepend the target to the arguments given in the makefile.configurations object,
// unless we want to parse for the full set of available targets.
if (forTargets) {
makeArgs.push("all");
} else {
let currentTarget: string | undefined = configuration.getCurrentTarget();
if (currentTarget) {
makeArgs.push(currentTarget);
}
}
// Include all the make arguments defined in makefile.configurations.makeArgs
makeArgs = makeArgs.concat(configuration.getConfigurationMakeArgs());
// If we are analyzing build targets, we need the following switches:
// --print-data-base (which generates verbose output where we parse targets from).
// --no-builtin-variables and --no-builtin-rules (to reduce the size of the
// output produced by --print-data-base and also to obtain a list of targets
// that make sense, skipping over implicit targets like objects from sources
// or binaries from objects and libs).
// --question (to not execute anything, for us equivalent of dry-run
// but without printing commands, which contributes again to a smaller output).
// If we are analyzing compiler/linker commands for IntelliSense and launch targets,
// we use --dry-run and anything from makefile.dryrunSwitches.
const dryrunSwitches: string[] | undefined =
configuration.getDryrunSwitches();
if (forTargets) {
makeArgs.push("--print-data-base");
makeArgs.push("--no-builtin-variables");
makeArgs.push("--no-builtin-rules");
makeArgs.push("--question");
logger.messageNoCR(
localize(
"generating.targets.with.command",
"Generating targets information with command: "
)
);
} else {
makeArgs.push("--dry-run");
// If this is not a clean configure, remove --always-make from the arguments list.
// We need to have --always-make in makefile.dryrunSwitches and remove it for not clean configure
// (as opposed to not having --always-make in makefile.dryrunSwitches and adding it for clean configure)
// because we want to avoid having 2 dryrun switches settings (one for clean and one for not clean configure)
// and also because the user needs to be able to remove --always-make from any make --dry-run invocation,
// if it causes trouble.
dryrunSwitches?.forEach((sw) => {
if (getConfigureIsClean() || (sw !== "--always-make" && sw !== "-B")) {
makeArgs.push(sw);
}
});
logger.messageNoCR(
localize(
"generating.configurating.cache",
"Generating {0}configuration cache with command: ",
getConfigureIsInBackground() ? "in the background a new " : ""
)
);
}
logger.message(
`'${configuration.getConfigurationMakeCommand()} ${makeArgs.join(" ")}'`
);
try {
let dryrunFile: string = forTargets ? "./targets.log" : "./dryrun.log";
let extensionOutputFolder: string | undefined =
configuration.getExtensionOutputFolder();
if (extensionOutputFolder) {
dryrunFile = path.join(extensionOutputFolder, dryrunFile);
}
dryrunFile = util.resolvePathToRoot(dryrunFile);
logger.message(
localize(
"writing.dry.run.output",
"Writing the dry-run output: {0}",
dryrunFile
)
);
const lineEnding: string =
process.platform === "win32" && process.env.MSYSTEM === undefined
? "\r\n"
: "\n";
util.writeFile(
dryrunFile,
`${configuration.getConfigurationMakeCommand()} ${makeArgs.join(
" "
)}${lineEnding}`
);
let completeOutput: string = "";
let stderrStr: string = "";
let heartBeat: number = Date.now();
let stdout: any = (result: string): void => {
const appendStr: string = `${result} ${lineEnding}`;
completeOutput += appendStr;
fs.appendFileSync(dryrunFile, appendStr);
progress.report({
increment: 1,
message:
dryRunString +
(recursive ? ` ${recursiveString}` : "") +
(forTargets ? ` ${forTargetsString}` : "" + "..."),
});
heartBeat = Date.now();
};
let stderr: any = (result: string): void => {
// We need this lineEnding to see more clearly the output coming from all these compilers and tools.
// But there is some unpredictability regarding how much these tools fragment their output, on various
// OSes and systems. To compare easily against a fix baseline, don't use lineEnding while running tests.
// So far this has been seen for stderr and not for stdout.
let appendStr: string = result;
if (process.env["MAKEFILE_TOOLS_TESTING"] !== "1") {
appendStr += lineEnding;
}
fs.appendFileSync(dryrunFile, appendStr);
stderrStr += appendStr;
// Sometimes there is useful information coming via the stderr
// (one example is even a bug of the make tool, because it reports
// "Entering directory" on stderr instead of stdout causing various issues).
completeOutput += appendStr;
};
const heartBeatTimeout: number = 30; // half minute. TODO: make this a setting
let timeout: NodeJS.Timeout = setInterval(function (): void {
let elapsedHeartBit: number = util.elapsedTimeSince(heartBeat);
if (elapsedHeartBit > heartBeatTimeout) {
vscode.window.showWarningMessage(
"Dryrun timeout. See Makefile Tools Output Channel for details."
);
logger.message(
localize(
"dryrun.timeout.verify",
"Dryrun timeout. Verify that the make command works properly in your development terminal (it could wait for stdin)."
)
);
logger.message(
localize(
"double.check.dryrun",
"Double check the dryrun output log: {0}",
dryrunFile
)
);
// It's enough to show this warning popup once.
clearInterval(timeout);
}
}, 5 * 1000);
// The dry-run analysis should operate on english.
const opts: util.ProcOptions = {
workingDirectory: util.getWorkspaceRoot(),
forceEnglish: true,
ensureQuoted: true,
stdoutCallback: stdout,
stderrCallback: stderr,
};
const result: util.SpawnProcessResult = await util.spawnChildProcess(
configuration.getConfigurationMakeCommand(),
makeArgs,
opts
);
clearInterval(timeout);
let elapsedTime: number = util.elapsedTimeSince(startTime);
logger.message(
localize(
"generating.dry.run.elapsed",
"Generating dry-run elapsed time: {0}",
elapsedTime
)
);
parseFile = dryrunFile;
parseContent = completeOutput;
// The error codes returned by the targets invocation (make -pRrq) mean something else
// (for example if targets are out of date). We can ignore the return code for this
// because it "can't fail". It represents only display of database and no targets are actually run.
// try syntax error
if (
result.returnCode !== ConfigureBuildReturnCodeTypes.success &&
!forTargets
) {
logger.message(
localize("make.dry.run.failed", "The make dry-run command failed.")
);
logger.message(
localize(
"intellisense.may.not.work",
"IntelliSense may work only partially or not at all."
)
);
logger.message(stderrStr);
// Report the standard dry-run error & guide only when the configure was not cancelled
// by the user (which causes retCode to be null).
// Also don't write the cache if this operation was cancelled
// because it may be incomplete and affect a future non clean configure.
if (result.returnCode !== null) {
util.reportDryRunError(dryrunFile);
}
}
curPID = -1;
return {
retc: result.returnCode,
elapsed: elapsedTime,
};
} catch (error) {
logger.message(error);
return {
retc: ConfigureBuildReturnCodeTypes.notFound,
elapsed: util.elapsedTimeSince(startTime),
};
}
}
export async function prePostConfigureHelper(
titles: { configuringScript: string; cancelling: string },
configureScriptMethod: (progress: vscode.Progress<{}>) => Promise<number>,
setConfigureScriptState: (value: boolean) => void,
logConfigureScriptTelemetry: (elapsedTime: number, exitCode: number) => void
): Promise<number> {
// No pre/post configure execution in untrusted workspaces.
// The check is needed also here in addition to disabling all UI and actions because,
// depending on settings, this can run automatically at project load.
if (!vscode.workspace.isTrusted) {
logger.message(
localize(
"no.script.can.run.untrusted",
"No script can run in an untrusted workspace."
)
);
return ConfigureBuildReturnCodeTypes.untrusted;
}
// check for being blocked by operations.
if (blockedByOp(Operations.preConfigure)) {
return ConfigureBuildReturnCodeTypes.blocked;
}
if (blockedByOp(Operations.postConfigure)) {
return ConfigureBuildReturnCodeTypes.blocked;
}
let configureScriptStartTime: number = Date.now();
let cancelConfigureScript: boolean = false;
try {
return await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: titles.configuringScript,
cancellable: true,
},
async (progress, cancel) => {
cancel.onCancellationRequested(async () => {
progress.report({
increment: 1,
message: localize(
"make.prePostConfigure.cancelling",
"Cancelling..."
),
});
cancelConfigureScript = true;
logger.message(
localize(
"attempting.to.kill.console.process",
"Attempting to kill the console process (PID = {0}) and all its children subprocesses...",
curPID
)
);
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: titles.cancelling,
cancellable: false,
},
async (progress) => {
await util.killTree(progress, curPID);
}
);
});
setConfigureScriptState(true);
let retc: number = await configureScriptMethod(progress);
if (cancelConfigureScript) {
retc = ConfigureBuildReturnCodeTypes.cancelled;
}
let configureScriptElapsedTime: number = util.elapsedTimeSince(
configureScriptStartTime
);
logConfigureScriptTelemetry(configureScriptElapsedTime, retc);
cancelConfigureScript = false;
if (retc !== ConfigureBuildReturnCodeTypes.success) {
logger.showOutputChannel();
}
return retc;
}
);
} finally {
setConfigureScriptState(false);
}
}
export async function preConfigure(triggeredBy: TriggeredBy): Promise<number> {
let scriptFile: string | undefined = configuration.getPreConfigureScript();
if (!scriptFile) {
vscode.window.showErrorMessage(
localize(
"no.preconfigure.script.provided",
"Pre-configure failed: no script provided."
)
);
logger.message(
localize(
"no.pre.configure.script.define.settings",
"No pre-configure script is set in settings. Make sure a pre-configuration script path is defined with makefile.preConfigureScript."
)
);
return ConfigureBuildReturnCodeTypes.notFound;
}
if (!util.checkFileExistsSync(scriptFile)) {
vscode.window.showErrorMessage(
localize(
"could.not.find.preconfigure.popup",
"Could not find pre-configure script."
)
);
logger.message(
localize(
"could.not.find.pre.configure.on.disk",
'Could not find the given pre-configure script "{0}" on disk.',
scriptFile
)
);
return ConfigureBuildReturnCodeTypes.notFound;
}
// Assert that scriptFile is not undefined at this point since we've checked above.
return await prePostConfigureHelper(
{
configuringScript: localize(