-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathutil.ts
1376 lines (1224 loc) · 43 KB
/
util.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.
// Helper APIs used by this extension
import * as configuration from "./configuration";
import * as fs from "fs";
import * as child_process from "child_process";
import * as logger from "./logger";
import * as make from "./make";
import * as path from "path";
import * as telemetry from "./telemetry";
import * as vscode from "vscode";
import * as nls from "vscode-nls";
import { extension } from "./extension";
nls.config({
messageFormat: nls.MessageFormat.bundle,
bundleFormat: nls.BundleFormat.standalone,
})();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
// C/CPP standard versions
export type StandardVersion =
| "c89"
| "c99"
| "c11"
| "c17"
| "c++98"
| "c++03"
| "c++11"
| "c++14"
| "c++17"
| "c++20"
| "c++23"
| "gnu89"
| "gnu99"
| "gnu11"
| "gnu17"
| "gnu++98"
| "gnu++03"
| "gnu++11"
| "gnu++14"
| "gnu++17"
| "gnu++20"
| "gnu++23"
| undefined;
// Supported target architectures (for code generated by the compiler)
export type TargetArchitecture = "x86" | "x64" | "arm" | "arm64" | undefined;
// IntelliSense modes
export type IntelliSenseMode =
| "msvc-x64"
| "msvc-x86"
| "msvc-arm"
| "msvc-arm64"
| "gcc-x64"
| "gcc-x86"
| "gcc-arm"
| "gcc-arm64"
| "clang-x64"
| "clang-x86"
| "clang-arm"
| "clang-arm64"
| undefined;
// Language types
export type Language = "c" | "cpp" | undefined;
export interface ProcOptions {
workingDirectory?: string;
forceEnglish?: boolean;
ensureQuoted?: boolean;
stdoutCallback?: (stdout: string) => void;
stderrCallback?: (stderr: string) => void;
}
export function checkFileExistsSync(filePath: string): boolean {
try {
// Often a path is added by the user to the PATH environment variable with surrounding quotes,
// especially on Windows where they get automatically added after TAB.
// These quotes become inner (not surrounding) quotes after we append various file names or do oher processing,
// making file sysem stats fail. Safe to remove here.
let filePathUnq: string = filePath;
filePathUnq = removeQuotes(filePathUnq);
return fs.statSync(filePathUnq).isFile();
} catch (e) {}
return false;
}
export function checkDirectoryExistsSync(directoryPath: string): boolean {
try {
return fs.statSync(directoryPath).isDirectory();
} catch (e) {}
return false;
}
export function createDirectorySync(directoryPath: string): boolean {
try {
fs.mkdirSync(directoryPath, { recursive: true });
return true;
} catch {}
return false;
}
export function deleteFileSync(filePath: string): void {
try {
fs.unlinkSync(filePath);
} catch (e) {}
}
export function readFile(filePath: string): string | undefined {
try {
if (checkFileExistsSync(filePath)) {
return fs.readFileSync(filePath).toString();
}
} catch (e) {}
return undefined;
}
export function writeFile(
filePath: string,
content: string
): string | undefined {
try {
fs.writeFileSync(filePath, content);
} catch (e) {}
return undefined;
}
// Get the platform-specific temporary directory
export function tmpDir(): string {
if (process.platform === "win32") {
return process.env["TEMP"] || "";
} else {
const xdg = process.env["XDG_RUNTIME_DIR"];
if (xdg) {
if (!fs.existsSync(xdg)) {
fs.mkdirSync(xdg);
}
return xdg;
}
return "/tmp";
}
}
// Returns the full path to a temporary script generated by the extension
// and used to parse any additional compiler switches that need to be sent to CppTools.
export function parseCompilerArgsScriptFile(): string {
const extensionPath = extension.extensionContext.extensionPath;
let scriptFile: string = path.join(
extensionPath,
"assets",
"parseCompilerArgs"
);
if (process.platform === "win32") {
scriptFile += ".bat";
} else {
scriptFile += ".sh";
}
return scriptFile;
}
export function getWorkspaceRoot(): string {
return vscode.workspace.workspaceFolders
? vscode.workspace.workspaceFolders[0].uri.fsPath
: "";
}
// Evaluate whether a string looks like a path or not,
// without using fs.stat, since dry-run may output tools
// that are not found yet at certain locations,
// without running the prep targets that would copy them there
export function looksLikePath(pathStr: string): boolean {
// TODO: to be implemented
return true;
}
// Evaluate whether the tool is invoked from the current directory
export function pathIsCurrentDirectory(pathStr: string): boolean {
// Ignore any spaces or tabs before the invocation
pathStr = pathStr.trimLeft();
if (pathStr === "") {
return true;
}
if (process.platform === "win32" && process.env.MSYSTEM === undefined) {
if (pathStr === ".\\") {
return true;
}
} else {
if (pathStr === "./") {
return true;
}
}
return false;
}
// Helper that searches for a tool in all the paths forming the PATH environment variable
// Returns the first one found or undefined if not found.
// TODO: implement a variation of this helper that scans on disk for the tools installed,
// to help when VSCode is not launched from the proper environment
export function toolPathInEnv(name: string): string | undefined {
let envPath: string | undefined = process.env["PATH"];
let envPathSplit: string[] = [];
if (envPath) {
envPathSplit = envPath.split(path.delimiter);
}
// todo: if the compiler is not found in path, scan on disk and point the user to all the options
// (the concept of kit for cmake extension)
return envPathSplit.find((p) => {
const fullPath: string = path.join(p, path.basename(name));
if (checkFileExistsSync(fullPath)) {
return fullPath;
}
});
}
function taskKill(pid: number): Promise<void> {
return new Promise<void>((resolve, reject) => {
child_process.exec(`taskkill /pid ${pid} /T /F`, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
export async function killTree(
progress: vscode.Progress<{}>,
pid: number
): Promise<void> {
if (process.platform === "win32") {
try {
await taskKill(pid);
} catch (e) {
logger.message(
localize(
"failed.to.kill.process",
"Failed to kill process {0}: {1}",
pid,
e
)
);
}
return;
}
let children: number[] = [];
let stdoutStr: string = "";
let stdout: any = (result: string): void => {
stdoutStr += result;
};
try {
const opts: ProcOptions = {
workingDirectory: getWorkspaceRoot(),
forceEnglish: true,
ensureQuoted: false,
stdoutCallback: stdout,
};
// pgrep should run on english, regardless of the system setting.
const result: SpawnProcessResult = await spawnChildProcess(
"pgrep",
["-P", pid.toString()],
opts
);
if (!!stdoutStr.length) {
children = stdoutStr
.split("\n")
.map((line: string) => Number.parseInt(line));
logger.message(
localize(
"found.children.subprocesses",
"Found children subprocesses: {0}.",
stdoutStr
)
);
for (const other of children) {
if (other) {
await killTree(progress, other);
}
}
}
} catch (e) {
logger.message(e.message);
throw e;
}
try {
logger.message(
localize("killing.process", "Killing process PID = {0}", pid)
);
progress.report({
increment: 1,
message: localize(
"utils.terminate.process",
"Terminating process PID=${0} ...",
pid
),
});
process.kill(pid, "SIGINT");
} catch (e) {
if (e.code !== "ESRCH") {
throw e;
}
}
}
// Environment variables helpers (inspired from CMake Tools utils).
export interface EnvironmentVariables {
[key: string]: string;
}
export function normalizeEnvironmentVarname(varname: string): string {
return process.platform === "win32" ? varname.toUpperCase() : varname;
}
export function mergeEnvironment(
...env: EnvironmentVariables[]
): EnvironmentVariables {
return env.reduce((acc, vars) => {
if (process.platform === "win32") {
// Env vars on windows are case insensitive, so we take the ones from
// active env and overwrite the ones in our current process env
const norm_vars: EnvironmentVariables = Object.getOwnPropertyNames(
vars
).reduce<EnvironmentVariables>((acc2, key: string) => {
acc2[normalizeEnvironmentVarname(key)] = vars[key];
return acc2;
}, {});
return { ...acc, ...norm_vars };
} else {
return { ...acc, ...vars };
}
}, {});
}
export let modifiedEnvironmentVariables: EnvironmentVariables = {};
export interface SpawnProcessResult {
returnCode: number;
signal: string;
}
// Helper to spawn a child process, hooked to callbacks that are processing stdout/stderr
// forceEnglish is true when the caller relies on parsing english words from the output.
export function spawnChildProcess(
processName: string,
args: string[],
options: ProcOptions
): Promise<SpawnProcessResult> {
const localeOverride: EnvironmentVariables = {
LANG: "C",
LC_ALL: "C",
};
// Use english language for this process regardless of the system setting.
const environment: EnvironmentVariables = options.forceEnglish
? localeOverride
: {};
const finalEnvironment: EnvironmentVariables = mergeEnvironment(
process.env as EnvironmentVariables,
environment
);
return new Promise<SpawnProcessResult>((resolve, reject) => {
// Honor the "terminal.integrated.automationShell.<platform>" setting.
// According to documentation (and settings.json schema), the three allowed values for <platform> are "windows", "linux" and "osx".
// child_process.SpawnOptions accepts a string (which can be read from the above setting) or the boolean true to let VSCode pick a default
// based on where it is running.
let shellType: string | undefined;
let shellPlatform: string =
process.platform === "win32"
? "windows"
: process.platform === "linux"
? "linux"
: "osx";
let workspaceConfiguration: vscode.WorkspaceConfiguration =
vscode.workspace.getConfiguration("terminal");
shellType =
workspaceConfiguration.get<string>(
`integrated.automationProfile.${shellPlatform}`
) || // automationShell is deprecated
workspaceConfiguration.get<string>(
`integrated.automationShell.${shellPlatform}`
); // and replaced with automationProfile
if (typeof shellType === "object") {
shellType = shellType["path"];
}
// Final quoting decisions for process name and args before being executed.
let qProcessName: string = options.ensureQuoted
? quoteStringIfNeeded(processName)
: processName;
let qArgs: string[] = options.ensureQuoted
? args.map((arg) => {
return quoteStringIfNeeded(arg);
})
: args;
if (options.ensureQuoted) {
logger.message(
localize(
"utils.quoting",
"Spawning child process with:\n process name: {0}\n process args: {1}\n working directory: {2}\n shell type: {3}",
qProcessName,
qArgs.join(","),
options.workingDirectory,
shellType || "default"
),
"Debug"
);
}
const child: child_process.ChildProcess = child_process.spawn(
qProcessName,
qArgs,
{
cwd: options.workingDirectory,
shell: shellType || true,
env: finalEnvironment,
}
);
if (child.pid) {
make.setCurPID(child.pid);
}
if (options.stdoutCallback) {
child.stdout?.on("data", (data) => {
options.stdoutCallback?.(`${data}`);
});
}
if (options.stderrCallback) {
child.stderr?.on("data", (data) => {
options.stderrCallback?.(`${data}`);
});
}
child.on("close", (returnCode: number, signal: string) => {
resolve({ returnCode, signal });
});
child.on("exit", (returnCode: number) => {
resolve({ returnCode, signal: "" });
});
if (child.pid === undefined) {
reject(new Error(`Failed to spawn process: ${processName} ${args}`));
}
});
}
export async function replaceCommands(
x: string,
safeCommands: string[] | undefined,
opt: child_process.SpawnOptions
): Promise<string> {
// Early exit, backtick doesn't apply on Windows
if (process.platform === "win32") {
return x;
}
const regex = /`([^\s]+)\s(.*?)`/g;
let match = regex.exec(x);
while (match !== null) {
if (safeCommands?.some((c) => c === match![1])) {
const output = await runCommand(`${match[1]} ${match[2]}`, opt);
x = x.replace(match[0], output);
} else {
const unsafeCommandMessage = localize(
"unsafe.command",
"Commands must be marked as safe before they will be executed in the shell. Add {0} to the {1} setting if this command is safe to execute",
match[1],
`'makefile.safeCommands'`
);
logger.message(unsafeCommandMessage, "Normal");
vscode.window.showWarningMessage(unsafeCommandMessage);
x = x.replace(match[0], `\`${match[1]} ${match[2]}\``);
}
match = regex.exec(x);
}
return x;
}
/**
* This is only designed to run for Linux for commands taken from a backtick context.
* @param x command
* @param opt SpawnOptions
* @returns resulting string
*/
async function runCommand(
x: string,
opt: child_process.SpawnOptions
): Promise<string> {
// backtick doesn't apply on Windows, return early
if (process.platform === "win32") {
return x;
}
const child = child_process.spawn("/bin/bash", ["-c", `"${x}"`], opt);
return new Promise<string>((resolve) => {
let output = "";
child.stdout?.on("data", (data) => {
output += data;
});
child.on("close", () => {
resolve(output.trim());
});
child.on("exit", () => {
resolve(output.trim());
});
});
}
// Helper to eliminate empty items in an array
export function dropNulls<T>(items: (T | null | undefined)[]): T[] {
return items.filter((item) => item !== null && item !== undefined) as T[];
}
// Convert a posix path (/home/dir1/dir2/file.ext) into windows path,
// by calling the cygpah which comes installed with MSYS/MinGW environments
// and which is also aware of the drive under which /home/ is placed.
// result: c:\msys64\home\dir1\dir2\file.ext
// Called usually for Windows subsystems: MinGW, CygWin.
export async function cygpath(pathStr: string): Promise<string> {
let windowsPath: string = pathStr;
let stdout: any = (result: string): void => {
windowsPath = result.replace(/\n/gm, ""); // remove the end of line
};
const opts: ProcOptions = {
workingDirectory: "",
forceEnglish: false,
ensureQuoted: false,
stdoutCallback: stdout,
};
// Running cygpath can use the system locale.
await spawnChildProcess("cygpath", [pathStr, "-w"], opts);
return windowsPath;
}
// Helper that transforms a posix path (used in various non windows environments on a windows system)
// into a windows style path.
export async function ensureWindowsPath(path: string): Promise<string> {
if (process.platform !== "win32" || !path.startsWith("/")) {
return path;
}
let winPath: string = path;
if (process.env.MSYSTEM !== undefined) {
// When in MSYS/MinGW/CygWin environments, cygpath can help transform into a windows path
// that we know CppTools will use when querying us.
winPath = await cygpath(winPath);
} else {
// Even in a pure windows environment, there are tools that may report posix paths.
// Instead of searching a cygpath tool somewhere, do the most basic transformations:
// Mount drives names like "cygdrive" or "mnt" can be ignored.
const mountDrives: string[] = ["cygdrive", "mnt"];
for (const drv of mountDrives) {
if (winPath.startsWith(`/${drv}`)) {
winPath = winPath.substr(drv.length + 1);
// Exit the loop, because we don't want to remove anything else
// in case the path happens to follow with a subfolder with the same name
// as other mountable drives for various systems/environments.
break;
}
}
// Remove the slash and add the : for the drive.
winPath = winPath.substr(1);
const driveEndIndex: number = winPath.search("/");
winPath =
winPath.substring(0, driveEndIndex) + ":" + winPath.substr(driveEndIndex);
// Replace / with \.
winPath = winPath.replace(/\//gm, "\\");
}
return winPath;
}
// Helper to reinterpret one relative path (to the given current path) printed by make as full path
export async function makeFullPath(
relPath: string,
curPath: string | undefined
): Promise<string> {
let fullPath: string = relPath;
if (!path.isAbsolute(fullPath) && curPath) {
fullPath = path.join(curPath, relPath);
}
// For win32, ensure we have a windows style path.
fullPath = await ensureWindowsPath(fullPath);
return fullPath;
}
// Helper to reinterpret the relative paths (to the given current path) printed by make as full paths
export async function makeFullPaths(
relPaths: string[],
curPath: string | undefined
): Promise<string[]> {
let fullPaths: string[] = [];
for (const p of relPaths) {
let fullPath: string = await makeFullPath(p, curPath);
fullPaths.push(fullPath);
}
return fullPaths;
}
// Helper to reinterpret one full path as relative to the given current path
export function makeRelPath(
fullPath: string,
curPath: string | undefined
): string {
let relPath: string = fullPath;
if (path.isAbsolute(fullPath) && curPath) {
relPath = path.relative(curPath, fullPath);
}
return relPath;
}
// Helper to reinterpret the relative paths (to the given current path) printed by make as full paths
export function makeRelPaths(
fullPaths: string[],
curPath: string | undefined
): string[] {
let relPaths: string[] = [];
fullPaths.forEach((p) => {
relPaths.push(makeRelPath(p, curPath));
});
return fullPaths;
}
// Helper to remove any quotes(", ' or `) from a given string
// because many file operations don't work properly with paths
// having quotes in the middle.
const quotesStr: string[] = ["'", '"', "`"];
export function removeQuotes(str: string): string {
for (const p in quotesStr) {
if (str.includes(quotesStr[p])) {
let regExpStr: string = `${quotesStr[p]}`;
let regExp: RegExp = RegExp(regExpStr, "g");
str = str.replace(regExp, "");
}
}
return str;
}
export function removeSplitUpParenthesis(strArray: string[]): string[] {
const resultArray: string[] = [];
for (const str of strArray) {
let result: string = str.trim();
if (result.startsWith("(") && !result.endsWith(")")) {
result = result.substring(1, str.length - 1);
} else if (result.endsWith(")") && !result.startsWith("(")) {
result = result.substring(0, str.length - 2);
}
resultArray.push(result.trim());
}
return resultArray;
}
// Remove only the quotes (", ' or `) that are surrounding the given string.
export function removeSurroundingQuotes(str: string): string {
let result: string = str.trim();
for (const p in quotesStr) {
if (result.startsWith(quotesStr[p]) && result.endsWith(quotesStr[p])) {
result = result.substring(1, str.length - 1);
return result;
}
}
return str;
}
// Quote given string if it contains space and is not quoted already
export function quoteStringIfNeeded(str: string): string {
// No need to quote if there is no space or ampersand present.
if (!str.includes(" ") && !str.includes("&")) {
return str;
}
// Return if already quoted.
for (const q in quotesStr) {
if (str.startsWith(quotesStr[q]) && str.endsWith(quotesStr[q])) {
return str;
}
}
// Quote and return.
return `"${str}"`;
}
export function replaceStringNotInQuotes(
value: string,
stringToBeReplaced: string,
replacementString: string
): string {
let withinDoubleQuotesString = false;
let withinSingleQuoteString = false;
let result = "";
let i = 0;
const stringToBeReplacedLength = stringToBeReplaced.length;
while (i < value.length) {
const testString = value.substring(i, stringToBeReplacedLength + i);
const char = value[i];
const isSingleQuote = char === "'";
const isDoubleQuote = char === '"';
const isStringToBeReplaced = testString === stringToBeReplaced;
const withinString = withinDoubleQuotesString || withinSingleQuoteString;
switch (withinString) {
case true:
result += char;
if (withinDoubleQuotesString) {
if (isDoubleQuote) {
withinDoubleQuotesString = false;
}
} else if (withinSingleQuoteString) {
if (isSingleQuote) {
withinSingleQuoteString = false;
}
}
i += 1;
break;
default:
if (isStringToBeReplaced) {
result += replacementString;
i += stringToBeReplacedLength;
} else {
result += char;
i += 1;
}
withinDoubleQuotesString ||= isDoubleQuote;
withinSingleQuoteString ||= isSingleQuote;
break;
}
}
return result;
}
// Used when constructing a regular expression from file names which can contain
// special characters (+, ", ...etc...).
const escapeChars: RegExp = /[\\\^\$\*\+\?\{\}\(\)\.\!\=\|\[\]\ \/]/; // characters that should be escaped.
export function escapeString(str: string): string {
let escapedString: string = "";
for (const char of str) {
if (char.match(escapeChars)) {
escapedString += `\\${char}`;
} else {
escapedString += char;
}
}
return escapedString;
}
export function elapsedTimeSince(start: number): number {
// Real elapsed times not useful in testing mode and we want to avoid diffs.
// We could alternatively disable the messages from being printed.
return process.env["MAKEFILE_TOOLS_TESTING"] === "1"
? 0
: (Date.now() - start) / 1000;
}
// Helper to evaluate whether two settings (objects or simple types) represent the same content.
// It recursively analyzes any inner subobjects and is also not affected
// by a different order of properties.
export function areEqual(setting1: any, setting2: any): boolean {
if (
setting1 === null ||
setting1 === undefined ||
setting2 === null ||
setting2 === undefined
) {
return setting1 === setting2;
}
// This is simply type
if (
typeof setting1 !== "function" &&
typeof setting1 !== "object" &&
typeof setting2 !== "function" &&
typeof setting2 !== "object"
) {
return setting1 === setting2;
}
let properties1: string[] = Object.getOwnPropertyNames(setting1);
let properties2: string[] = Object.getOwnPropertyNames(setting2);
if (properties1.length !== properties2.length) {
return false;
}
for (let p: number = 0; p < properties1.length; p++) {
let property: string = properties1[p];
let isEqual: boolean;
if (
typeof setting1[property] === "object" &&
typeof setting2[property] === "object"
) {
isEqual = areEqual(setting1[property], setting2[property]);
} else {
isEqual = setting1[property] === setting2[property];
}
if (!isEqual) {
return false;
}
}
return true;
}
// Answers whether the given object has at least one property.
export function hasProperties(obj: any): boolean {
if (obj === null || obj === undefined) {
return false;
}
let props: string[] = Object.getOwnPropertyNames(obj);
return props && props.length > 0;
}
// Apply any properties from source to destination, logging for overwrite.
// To make things simpler for the caller, create a valid dst if given null or undefined.
export function mergeProperties(dst: any, src: any): any {
let props: string[] = src ? Object.getOwnPropertyNames(src) : [];
props.forEach((prop) => {
if (!dst) {
dst = {};
}
if (dst[prop] !== undefined) {
logger.message(
localize(
"utils.overwriting.property",
"Destination object already has property {0} set to {1}. Overwriting from source with {2}",
prop,
dst[prop],
src[prop]
),
"Debug"
);
}
dst[prop] = src[prop];
});
return dst;
}
export function removeDuplicates(src: string[]): string[] {
let seen: { [key: string]: boolean } = {};
let result: string[] = [];
src.forEach((item) => {
if (!seen[item]) {
seen[item] = true;
result.push(item);
}
});
return result;
}
export function sortAndRemoveDuplicates(src: string[]): string[] {
return removeDuplicates(src.sort());
}
export function reportDryRunError(dryrunOutputFile: string): void {
logger.message(
localize(
"utils.dryrun.detailed.output",
"You can see the detailed dry-run output at {0}",
dryrunOutputFile
)
);
logger.message(
localize(
"utils.dryrun.error.environment",
"Make sure that the extension is invoking the same make command as in your development prompt environment."
)
);
logger.message(
localize(
"utils.dryrun.error.makefile",
"You may need to define or tweak a custom makefile configuration in settings via 'makefile.configurations' like described here: [link]"
)
);
logger.message(
localize(
"utils.dryrun.error.knownissues",
"Also make sure your code base does not have any known issues with the dry-run switches used by this extension (makefile.dryrunSwitches)."
)
);
logger.message(
localize(
"utils.dryrun.error.github",
"If you are not able to fix the dry-run, open a GitHub issue in Makefile Tools repo: https://github.com/microsoft/vscode-makefile-tools/issues"
)
);
}
// Helper to make paths absolute until the extension handles variables expansion.
export function resolvePathToRoot(relPath: string): string {
if (!path.isAbsolute(relPath)) {
return path.join(getWorkspaceRoot(), relPath);
}
return relPath;
}
// Return the string representing the user home location.
// Inspired from CMake Tools. TODO: implement more such paths and refactor into a separate class.
export function userHome(): string {
if (process.platform === "win32") {
return path.join(
process.env["HOMEDRIVE"] || "C:",
process.env["HOMEPATH"] || "Users\\Public"
);
} else {
return process.env["HOME"] || process.env["PROFILE"] || "";
}
}
// Helper to correctly interpret boolean values out of strings.
// Currently used during settings variable expansion.
export function booleanify(value: string): boolean {
const truthy: string[] = ["true", "True", "1"];
return truthy.includes(value);
}
// Read setting from workspace settings and expand according to various supported patterns.
// Do this for the simple types (converting to boolean or numerals when the varexp syntax
// is used on such types of settings) and for arrays or objects, expand recursively
// until we reach the simple types for submembers. This handles any structure.
export async function getExpandedSetting<T>(
settingId: string,
propSchema?: any
): Promise<T | undefined> {
let workspaceConfiguration: vscode.WorkspaceConfiguration =
vscode.workspace.getConfiguration("makefile");
let settingVal: any | undefined = workspaceConfiguration.get<T>(settingId);
if (!propSchema) {
propSchema = thisExtensionPackage().contributes.configuration.properties;
propSchema = propSchema.properties
? propSchema.properties[`makefile.${settingId}`]
: propSchema[`makefile.${settingId}`];
}
// Read what's at settingId in the workspace settings and for objects and arrays of complex types make sure
// to copy into a new counterpart that we will modify, because we don't want to persist expanded values in settings.
let copySettingVal: any | undefined;
if (propSchema && propSchema.type === "array") {
// A simple .concat() is not enough. We need to push(Object.assign) on all object entries in the array.
copySettingVal = [];
(settingVal as any[]).forEach((element) => {
let copyElement: any = {};
copyElement =
typeof element === "object"
? Object.assign(copyElement, element)
: element;