-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcommon.ts
More file actions
1852 lines (1676 loc) · 68.9 KB
/
common.ts
File metadata and controls
1852 lines (1676 loc) · 68.9 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
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import * as assert from 'assert';
import * as child_process from 'child_process';
import * as jsonc from 'comment-json';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as tmp from 'tmp';
import * as vscode from 'vscode';
import { DocumentFilter, Range } from 'vscode-languageclient';
import * as nls from 'vscode-nls';
import { TargetPopulation } from 'vscode-tas-client';
import * as which from "which";
import { ManualPromise } from './Utility/Async/manualPromise';
import { isWindows } from './constants';
import { getOutputChannelLogger, showOutputChannel } from './logger';
import { PlatformInformation } from './platform';
import * as Telemetry from './telemetry';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
export const failedToParseJson: string = localize("failed.to.parse.json", "Failed to parse json file, possibly due to comments or trailing commas.");
export type Mutable<T> = {
// eslint-disable-next-line @typescript-eslint/array-type
-readonly [P in keyof T]: T[P] extends ReadonlyArray<infer U> ? Mutable<U>[] : Mutable<T[P]>
};
export let extensionPath: string;
export let extensionContext: vscode.ExtensionContext | undefined;
export function setExtensionContext(context: vscode.ExtensionContext): void {
extensionContext = context;
extensionPath = extensionContext.extensionPath;
}
export function setExtensionPath(path: string): void {
extensionPath = path;
}
let cachedClangFormatPath: string | undefined;
export function getCachedClangFormatPath(): string | undefined {
return cachedClangFormatPath;
}
export function setCachedClangFormatPath(path: string): void {
cachedClangFormatPath = path;
}
let cachedClangTidyPath: string | undefined;
export function getCachedClangTidyPath(): string | undefined {
return cachedClangTidyPath;
}
export function setCachedClangTidyPath(path: string): void {
cachedClangTidyPath = path;
}
// Use this package.json to read values
export const packageJson: any = vscode.extensions.getExtension("ms-vscode.cpptools")?.packageJSON;
// Use getRawSetting to get subcategorized settings from package.json.
// This prevents having to iterate every time we search.
let flattenedPackageJson: Map<string, any>;
export function getRawSetting(key: string, breakIfMissing: boolean = false): any {
if (flattenedPackageJson === undefined) {
flattenedPackageJson = new Map();
for (const subheading of packageJson.contributes.configuration) {
for (const setting in subheading.properties) {
flattenedPackageJson.set(setting, subheading.properties[setting]);
}
}
}
const result = flattenedPackageJson.get(key);
if (result === undefined && breakIfMissing) {
// eslint-disable-next-line no-debugger
debugger; // The setting does not exist in package.json. Check the `key`.
}
return result;
}
export async function getRawJson(path: string | undefined): Promise<any> {
if (!path) {
return {};
}
const fileExists: boolean = await checkFileExists(path);
if (!fileExists) {
return {};
}
const fileContents: string = await readFileText(path);
let rawElement: any = {};
try {
rawElement = jsonc.parse(fileContents, undefined, true);
} catch {
throw new Error(failedToParseJson);
}
return rawElement;
}
// This function is used to stringify the rawPackageJson.
// Do not use with util.packageJson or else the expanded
// package.json will be written back.
export function stringifyPackageJson(packageJson: string): string {
return JSON.stringify(packageJson, null, 2);
}
export function getExtensionFilePath(extensionfile: string): string {
return path.resolve(extensionPath, extensionfile);
}
export function getPackageJsonPath(): string {
return getExtensionFilePath("package.json");
}
export function getJsonPath(jsonFilaName: string, workspaceFolder?: vscode.WorkspaceFolder): string | undefined {
const editor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (!editor) {
return undefined;
}
const folder: vscode.WorkspaceFolder | undefined = workspaceFolder ? workspaceFolder : vscode.workspace.getWorkspaceFolder(editor.document.uri);
if (!folder) {
return undefined;
}
return path.join(folder.uri.fsPath, ".vscode", jsonFilaName);
}
export function getVcpkgPathDescriptorFile(): string {
if (process.platform === 'win32') {
const pathPrefix: string | undefined = process.env.LOCALAPPDATA;
if (!pathPrefix) {
throw new Error("Unable to read process.env.LOCALAPPDATA");
}
return path.join(pathPrefix, "vcpkg/vcpkg.path.txt");
} else {
const pathPrefix: string = os.homedir();
return path.join(pathPrefix, ".vcpkg/vcpkg.path.txt");
}
}
let vcpkgRoot: string | undefined;
export function getVcpkgRoot(): string {
if (!vcpkgRoot && vcpkgRoot !== "") {
vcpkgRoot = "";
// Check for vcpkg instance.
if (fs.existsSync(getVcpkgPathDescriptorFile())) {
let vcpkgRootTemp: string = fs.readFileSync(getVcpkgPathDescriptorFile()).toString();
vcpkgRootTemp = vcpkgRootTemp.trim();
if (fs.existsSync(vcpkgRootTemp)) {
vcpkgRoot = path.join(vcpkgRootTemp, "/installed").replace(/\\/g, "/");
}
}
}
return vcpkgRoot;
}
/**
* This is a fuzzy determination of whether a uri represents a header file.
* For the purposes of this function, a header file has no extension, or an extension that begins with the letter 'h'.
* @param document The document to check.
*/
export function isHeaderFile(uri: vscode.Uri): boolean {
const fileExt: string = path.extname(uri.fsPath);
const fileExtLower: string = fileExt.toLowerCase();
return !fileExt || [".cuh", ".hpp", ".hh", ".hxx", ".h++", ".hp", ".h", ".inl", ".ipp", ".tcc", ".txx", ".tpp", ".tlh", ".tli", ""].some(ext => fileExtLower === ext);
}
export function isCppFile(uri: vscode.Uri): boolean {
const fileExt: string = path.extname(uri.fsPath);
const fileExtLower: string = fileExt.toLowerCase();
return (fileExt === ".C") || [".cu", ".cpp", ".cc", ".cxx", ".c++", ".cp", ".ii", ".ino", ".sycl"].some(ext => fileExtLower === ext);
}
export function isCFile(uri: vscode.Uri): boolean {
const fileExt: string = path.extname(uri.fsPath);
const fileExtLower: string = fileExt.toLowerCase();
return fileExt === ".c" || fileExtLower === ".i";
}
export function isCppOrCFile(uri: vscode.Uri | undefined): boolean {
if (!uri) {
return false;
}
return isCppFile(uri) || isCFile(uri);
}
export function isFolderOpen(uri: vscode.Uri): boolean {
const folder: vscode.WorkspaceFolder | undefined = vscode.workspace.getWorkspaceFolder(uri);
return folder ? true : false;
}
export function isEditorFileCpp(file: string): boolean {
const editor: vscode.TextEditor | undefined = vscode.window.visibleTextEditors.find(e => e.document.uri.toString() === file);
if (!editor) {
return false;
}
return editor.document.languageId === "cpp";
}
// If it's C, C++, or Cuda.
export function isCpp(document: vscode.TextDocument): boolean {
return document.uri.scheme === "file" &&
(document.languageId === "c" || document.languageId === "cpp" || document.languageId === "cuda-cpp");
}
export function isCppPropertiesJson(document: vscode.TextDocument): boolean {
return document.uri.scheme === "file" && (document.languageId === "json" || document.languageId === "jsonc") &&
document.fileName.endsWith("c_cpp_properties.json");
}
let isWorkspaceCpp: boolean = false;
export function setWorkspaceIsCpp(): void {
if (!isWorkspaceCpp) {
isWorkspaceCpp = true;
}
}
export function getWorkspaceIsCpp(): boolean {
return isWorkspaceCpp;
}
export function isCppOrRelated(document: vscode.TextDocument): boolean {
return isCpp(document) || isCppPropertiesJson(document) || (document.uri.scheme === "output" && document.uri.fsPath.startsWith("extension-output-ms-vscode.cpptools")) ||
(isWorkspaceCpp && (document.languageId === "json" || document.languageId === "jsonc") &&
((document.fileName.endsWith("settings.json") && (document.uri.scheme === "file" || document.uri.scheme === "vscode-userdata")) ||
(document.uri.scheme === "file" && document.fileName.endsWith(".code-workspace"))));
}
let isExtensionNotReadyPromptDisplayed: boolean = false;
export const extensionNotReadyString: string = localize("extension.not.ready", 'The C/C++ extension is still installing. See the output window for more information.');
export function displayExtensionNotReadyPrompt(): void {
if (!isExtensionNotReadyPromptDisplayed) {
isExtensionNotReadyPromptDisplayed = true;
showOutputChannel();
void getOutputChannelLogger().showInformationMessage(extensionNotReadyString).then(
() => { isExtensionNotReadyPromptDisplayed = false; },
() => { isExtensionNotReadyPromptDisplayed = false; }
);
}
}
// This Progress global state tracks how far users are able to get before getting blocked.
// Users start with a progress of 0 and it increases as they get further along in using the tool.
// This eliminates noise/problems due to re-installs, terminated installs that don't send errors,
// errors followed by workarounds that lead to success, etc.
const progressDebuggerStarted: number = 50;
const progressDebuggerSuccess: number = 100;
const progressExecutableStarted: number = 150;
const progressCopilotSuccess: number = 180;
const progressExecutableSuccess: number = 200;
const progressParseRootSuccess: number = 300;
const progressLanguageServiceDisabled: number = 400;
const progressIntelliSenseNoSquiggles: number = 1000;
// Might add more IntelliSense progress measurements later.
// IntelliSense progress is separate from the activation progress, because parse root can occur afterwards.
const activationProgressStr: string = "CPP." + packageJson.version + ".Progress";
const intelliSenseProgressStr: string = "CPP." + packageJson.version + ".IntelliSenseProgress";
export function getProgress(): number {
return extensionContext ? extensionContext.globalState.get<number>(activationProgressStr, -1) : -1;
}
export function getIntelliSenseProgress(): number {
return extensionContext ? extensionContext.globalState.get<number>(intelliSenseProgressStr, -1) : -1;
}
export function setProgress(progress: number): void {
if (extensionContext && getProgress() < progress) {
void extensionContext.globalState.update(activationProgressStr, progress);
const telemetryProperties: Record<string, string> = {};
let progressName: string | undefined;
switch (progress) {
case 0: progressName = "activation started"; break;
case progressDebuggerStarted: progressName = "debugger started"; break;
case progressDebuggerSuccess: progressName = "debugger succeeded"; break;
case progressExecutableStarted: progressName = "executable started"; break;
case progressCopilotSuccess: progressName = "copilot succeeded"; break;
case progressExecutableSuccess: progressName = "executable succeeded"; break;
case progressParseRootSuccess: progressName = "parse root succeeded"; break;
case progressLanguageServiceDisabled: progressName = "language service disabled"; break;
}
if (progressName) {
telemetryProperties.progress = progressName;
}
Telemetry.logDebuggerEvent("progress", telemetryProperties);
}
}
export function setIntelliSenseProgress(progress: number): void {
if (extensionContext && getIntelliSenseProgress() < progress) {
void extensionContext.globalState.update(intelliSenseProgressStr, progress);
const telemetryProperties: Record<string, string> = {};
let progressName: string | undefined;
switch (progress) {
case progressIntelliSenseNoSquiggles: progressName = "IntelliSense no squiggles"; break;
}
if (progressName) {
telemetryProperties.progress = progressName;
}
Telemetry.logDebuggerEvent("progress", telemetryProperties);
}
}
export function getProgressDebuggerStarted(): number { return progressDebuggerStarted; } // Debugger initialization was started.
export function getProgressDebuggerSuccess(): number { return progressDebuggerSuccess; } // Debugger was successfully initialized.
export function getProgressExecutableStarted(): number { return progressExecutableStarted; } // The extension was activated and starting the executable was attempted.
export function getProgressCopilotSuccess(): number { return progressCopilotSuccess; } // Copilot activation was successful.
export function getProgressExecutableSuccess(): number { return progressExecutableSuccess; } // Starting the exe was successful (i.e. not blocked by 32-bit or glibc < 2.18 on Linux)
export function getProgressParseRootSuccess(): number { return progressParseRootSuccess; } // Parse root was successful (i.e. not blocked by processing taking too long).
export function getProgressLanguageServiceDisabled(): number { return progressLanguageServiceDisabled; } // The user disabled the language service.
export function getProgressIntelliSenseNoSquiggles(): number { return progressIntelliSenseNoSquiggles; } // IntelliSense was successful and the user got no squiggles.
export function isUri(input: any): input is vscode.Uri {
return input && input instanceof vscode.Uri;
}
export function isString(input: any): input is string {
return typeof input === "string";
}
export function isNumber(input: any): input is number {
return typeof input === "number";
}
export function isBoolean(input: any): input is boolean {
return typeof input === "boolean";
}
export function isObject(input: any): boolean {
return input !== null && typeof input === "object" && !isArray(input);
}
export function isArray(input: any): input is any[] {
return Array.isArray(input);
}
export function isOptionalString(input: any): input is string | undefined {
return input === undefined || isString(input);
}
export function isArrayOfString(input: any): input is string[] {
return isArray(input) && input.every(isString);
}
// Validates whether the given object is a valid mapping of key and value type.
// EX: {"key": true, "key2": false} should return true for keyType = string and valueType = boolean.
export function isValidMapping(value: any, isValidKey: (key: any) => boolean, isValidValue: (value: any) => boolean): value is object {
if (isObject(value)) {
return Object.entries(value).every(([key, val]) => isValidKey(key) && isValidValue(val));
}
return false;
}
export function isOptionalArrayOfString(input: any): input is string[] | undefined {
return input === undefined || isArrayOfString(input);
}
export function resolveCachePath(input: string | undefined, additionalEnvironment: Record<string, string | string[]>): string {
let resolvedPath: string = "";
if (!input || input.trim() === "") {
// If no path is set, return empty string to language service process, where it will set the default path as
// Windows: %LocalAppData%/Microsoft/vscode-cpptools/
// Linux and Mac: ~/.vscode-cpptools/
return resolvedPath;
}
resolvedPath = resolveVariables(input, additionalEnvironment);
return resolvedPath;
}
export function defaultExePath(): string {
const exePath: string = path.join('${fileDirname}', '${fileBasenameNoExtension}');
return isWindows ? exePath + '.exe' : exePath;
}
// Pass in 'arrayResults' if a string[] result is possible and a delimited string result is undesirable.
// The string[] result will be copied into 'arrayResults'.
export function resolveVariables(input: string | undefined, additionalEnvironment?: Record<string, string | string[]>, arrayResults?: string[]): string {
if (!input) {
return "";
}
// jsonc parser may assign a non-string object to a string.
// TODO: https://github.com/microsoft/vscode-cpptools/issues/9414
if (!isString(input)) {
const inputAny: any = input;
input = inputAny.toString();
return input ?? "";
}
// Replace environment and configuration variables.
const regexp: () => RegExp = () => /\$\{((env|config|workspaceFolder)(\.|:))?(.*?)\}/g;
let ret: string = input;
const cycleCache = new Set<string>();
while (!cycleCache.has(ret)) {
cycleCache.add(ret);
ret = ret.replace(regexp(), (match: string, ignored1: string, varType: string, ignored2: string, name: string) => {
// Historically, if the variable didn't have anything before the "." or ":"
// it was assumed to be an environment variable
if (!varType) {
varType = "env";
}
let newValue: string | undefined;
switch (varType) {
case "env": {
if (additionalEnvironment) {
const v: string | string[] | undefined = additionalEnvironment[name];
if (isString(v)) {
newValue = v;
} else if (input === match && isArrayOfString(v)) {
if (arrayResults !== undefined) {
arrayResults.push(...v);
newValue = "";
break;
} else {
newValue = v.join(path.delimiter);
}
}
}
if (newValue === undefined) {
newValue = process.env[name];
}
break;
}
case "config": {
const config: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration();
if (config) {
newValue = config.get<string>(name);
}
break;
}
case "workspaceFolder": {
// Only replace ${workspaceFolder:name} variables for now.
// We may consider doing replacement of ${workspaceFolder} here later, but we would have to update the language server and also
// intercept messages with paths in them and add the ${workspaceFolder} variable back in (e.g. for light bulb suggestions)
if (name && vscode.workspace && vscode.workspace.workspaceFolders) {
const folder: vscode.WorkspaceFolder | undefined = vscode.workspace.workspaceFolders.find(folder => folder.name.toLocaleLowerCase() === name.toLocaleLowerCase());
if (folder) {
newValue = folder.uri.fsPath;
}
}
break;
}
default: { assert.fail("unknown varType matched"); }
}
return newValue !== undefined ? newValue : match;
});
}
return resolveHome(ret);
}
export function resolveVariablesArray(variables: string[] | undefined, additionalEnvironment?: Record<string, string | string[]>): string[] {
let result: string[] = [];
if (variables) {
variables.forEach(variable => {
const variablesResolved: string[] = [];
const variableResolved: string = resolveVariables(variable, additionalEnvironment, variablesResolved);
result = result.concat(variablesResolved.length === 0 ? variableResolved : variablesResolved);
});
}
return result;
}
// Resolve '~' at the start of the path.
export function resolveHome(filePath: string): string {
return filePath.replace(/^\~/g, os.homedir());
}
export function asFolder(uri: vscode.Uri): string {
let result: string = uri.toString();
if (!result.endsWith('/')) {
result += '/';
}
return result;
}
/**
* get the default open command for the current platform
*/
export function getOpenCommand(): string {
if (os.platform() === 'win32') {
return 'explorer';
} else if (os.platform() === 'darwin') {
return '/usr/bin/open';
} else {
return '/usr/bin/xdg-open';
}
}
export function getDebugAdaptersPath(file: string): string {
return path.resolve(getExtensionFilePath("debugAdapters"), file);
}
export async function fsStat(filePath: fs.PathLike): Promise<fs.Stats | undefined> {
let stats: fs.Stats | undefined;
try {
stats = await fs.promises.stat(filePath);
} catch {
// File doesn't exist
return undefined;
}
return stats;
}
export async function checkPathExists(filePath: string): Promise<boolean> {
return !!await fsStat(filePath);
}
/** Test whether a file exists */
export async function checkFileExists(filePath: string): Promise<boolean> {
const stats: fs.Stats | undefined = await fsStat(filePath);
return !!stats && stats.isFile();
}
/** Test whether a file exists */
export async function checkExecutableWithoutExtensionExists(filePath: string): Promise<boolean> {
if (await checkFileExists(filePath)) {
return true;
}
if (os.platform() === 'win32') {
if (filePath.length > 4) {
const possibleExtension: string = filePath.substring(filePath.length - 4).toLowerCase();
if (possibleExtension === ".exe" || possibleExtension === ".cmd" || possibleExtension === ".bat") {
return false;
}
}
if (await checkFileExists(filePath + ".exe")) {
return true;
}
if (await checkFileExists(filePath + ".cmd")) {
return true;
}
if (await checkFileExists(filePath + ".bat")) {
return true;
}
}
return false;
}
/** Test whether a directory exists */
export async function checkDirectoryExists(dirPath: string): Promise<boolean> {
const stats: fs.Stats | undefined = await fsStat(dirPath);
return !!stats && stats.isDirectory();
}
export function createDirIfNotExistsSync(filePath: string | undefined): void {
if (!filePath) {
return;
}
const dirPath: string = path.dirname(filePath);
if (!checkDirectoryExistsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
}
export function checkFileExistsSync(filePath: string): boolean {
try {
return fs.statSync(filePath).isFile();
} catch {
return false;
}
}
export function checkExecutableWithoutExtensionExistsSync(filePath: string): boolean {
if (checkFileExistsSync(filePath)) {
return true;
}
if (os.platform() === 'win32') {
if (filePath.length > 4) {
const possibleExtension: string = filePath.substring(filePath.length - 4).toLowerCase();
if (possibleExtension === ".exe" || possibleExtension === ".cmd" || possibleExtension === ".bat") {
return false;
}
}
if (checkFileExistsSync(filePath + ".exe")) {
return true;
}
if (checkFileExistsSync(filePath + ".cmd")) {
return true;
}
if (checkFileExistsSync(filePath + ".bat")) {
return true;
}
}
return false;
}
/** Test whether a directory exists */
export function checkDirectoryExistsSync(dirPath: string): boolean {
try {
return fs.statSync(dirPath).isDirectory();
} catch {
return false;
}
}
/** Test whether a relative path exists */
export function checkPathExistsSync(path: string, relativePath: string, _isWindows: boolean, isCompilerPath: boolean): { pathExists: boolean; path: string } {
let pathExists: boolean = true;
const existsWithExeAdded: (path: string) => boolean = (path: string) => isCompilerPath && _isWindows && fs.existsSync(path + ".exe");
if (!fs.existsSync(path)) {
if (existsWithExeAdded(path)) {
path += ".exe";
} else if (!relativePath) {
pathExists = false;
} else {
// Check again for a relative path.
relativePath = relativePath + path;
if (!fs.existsSync(relativePath)) {
if (existsWithExeAdded(path)) {
path += ".exe";
} else {
pathExists = false;
}
} else {
path = relativePath;
}
}
}
return { pathExists, path };
}
/** Read the files in a directory */
export function readDir(dirPath: string): Promise<string[]> {
return new Promise((resolve) => {
fs.readdir(dirPath, (err, list) => {
resolve(list);
});
});
}
/** Reads the content of a text file */
export function readFileText(filePath: string, encoding: BufferEncoding = "utf8"): Promise<string> {
return new Promise<string>((resolve, reject) => {
fs.readFile(filePath, { encoding }, (err: any, data: any) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
/** Writes content to a text file */
export function writeFileText(filePath: string, content: string, encoding: BufferEncoding = "utf8"): Promise<void> {
const folders: string[] = filePath.split(path.sep).slice(0, -1);
if (folders.length) {
// create folder path if it doesn't exist
folders.reduce((previous, folder) => {
const folderPath: string = previous + path.sep + folder;
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath);
}
return folderPath;
});
}
return new Promise<void>((resolve, reject) => {
fs.writeFile(filePath, content, { encoding }, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
export function deleteFile(filePath: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
if (fs.existsSync(filePath)) {
fs.unlink(filePath, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
} else {
resolve();
}
});
}
export function deleteDirectory(directoryPath: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
if (fs.existsSync(directoryPath)) {
fs.rmdir(directoryPath, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
} else {
resolve();
}
});
}
export function getReadmeMessage(): string {
const readmePath: string = getExtensionFilePath("README.md");
const readmeMessage: string = localize("refer.read.me", "Please refer to {0} for troubleshooting information. Issues can be created at {1}", readmePath, "https://github.com/Microsoft/vscode-cpptools/issues");
return readmeMessage;
}
/** Used for diagnostics only */
export function logToFile(message: string): void {
const logFolder: string = getExtensionFilePath("extension.log");
fs.writeFileSync(logFolder, `${message}${os.EOL}`, { flag: 'a' });
}
export function execChildProcess(process: string, workingDirectory?: string, channel?: vscode.OutputChannel): Promise<string> {
return new Promise<string>((resolve, reject) => {
child_process.exec(process, { cwd: workingDirectory, maxBuffer: 500 * 1024 }, (error: Error | null, stdout: string, stderr: string) => {
if (channel) {
let message: string = "";
let err: boolean = false;
if (stdout && stdout.length > 0) {
message += stdout;
}
if (stderr && stderr.length > 0) {
message += stderr;
err = true;
}
if (error) {
message += error.message;
err = true;
}
if (err) {
channel.append(message);
channel.show();
}
}
if (error) {
reject(error);
return;
}
if (stderr && stderr.length > 0) {
reject(new Error(stderr));
return;
}
resolve(stdout);
});
});
}
export interface ProcessReturnType {
succeeded: boolean;
exitCode?: number | NodeJS.Signals;
output: string;
outputError: string;
}
export async function spawnChildProcess(program: string, args: string[] = [], continueOn?: string, skipLogging?: boolean, cancellationToken?: vscode.CancellationToken): Promise<ProcessReturnType> {
// Do not use CppSettings to avoid circular require()
if (skipLogging === undefined || !skipLogging) {
getOutputChannelLogger().appendLineAtLevel(5, `$ ${program} ${args.join(' ')}`);
}
const programOutput: ProcessOutput = await spawnChildProcessImpl(program, args, continueOn, skipLogging, cancellationToken);
const exitCode: number | NodeJS.Signals | undefined = programOutput.exitCode;
if (programOutput.exitCode) {
return { succeeded: false, exitCode, outputError: programOutput.stderr, output: programOutput.stderr || programOutput.stdout || localize('process.exited', 'Process exited with code {0}', exitCode) };
} else {
let stdout: string;
if (programOutput.stdout.length) {
// Type system doesn't work very well here, so we need call toString
stdout = programOutput.stdout;
} else {
stdout = localize('process.succeeded', 'Process executed successfully.');
}
return { succeeded: true, exitCode, outputError: programOutput.stderr, output: stdout };
}
}
interface ProcessOutput {
exitCode?: number | NodeJS.Signals;
stdout: string;
stderr: string;
}
async function spawnChildProcessImpl(program: string, args: string[], continueOn?: string, skipLogging?: boolean, cancellationToken?: vscode.CancellationToken): Promise<ProcessOutput> {
const result = new ManualPromise<ProcessOutput>();
let proc: child_process.ChildProcess;
if (await isExecutable(program)) {
proc = child_process.spawn(`.${isWindows ? '\\' : '/'}${path.basename(program)}`, args, { shell: true, cwd: path.dirname(program) });
} else {
proc = child_process.spawn(program, args, { shell: true });
}
const cancellationTokenListener: vscode.Disposable | undefined = cancellationToken?.onCancellationRequested(() => {
getOutputChannelLogger().appendLine(localize('killing.process', 'Killing process {0}', program));
proc.kill();
});
const clean = () => {
proc.removeAllListeners();
if (cancellationTokenListener) {
cancellationTokenListener.dispose();
}
};
let stdout: string = '';
let stderr: string = '';
if (proc.stdout) {
proc.stdout.on('data', data => {
const str: string = data.toString();
if (skipLogging === undefined || !skipLogging) {
getOutputChannelLogger().appendAtLevel(1, str);
}
stdout += str;
if (continueOn) {
const continueOnReg: string = escapeStringForRegex(continueOn);
if (stdout.search(continueOnReg)) {
result.resolve({ stdout: stdout.trim(), stderr: stderr.trim() });
}
}
});
}
if (proc.stderr) {
proc.stderr.on('data', data => stderr += data.toString());
}
proc.on('close', (code, signal) => {
clean();
result.resolve({ exitCode: code || signal || undefined, stdout: stdout.trim(), stderr: stderr.trim() });
});
proc.on('error', error => {
clean();
result.reject(error);
});
return result;
}
/**
* @param permission fs file access constants: https://nodejs.org/api/fs.html#file-access-constants
*/
export function pathAccessible(filePath: string, permission: number = fs.constants.F_OK): Promise<boolean> {
if (!filePath) { return Promise.resolve(false); }
return new Promise(resolve => fs.access(filePath, permission, err => resolve(!err)));
}
export function isExecutable(file: string): Promise<boolean> {
return pathAccessible(file, fs.constants.X_OK);
}
export async function allowExecution(file: string): Promise<void> {
if (process.platform !== 'win32') {
const exists: boolean = await checkFileExists(file);
if (exists) {
const isExec: boolean = await isExecutable(file);
if (!isExec) {
await chmodAsync(file, '755');
}
} else {
getOutputChannelLogger().appendLine("");
getOutputChannelLogger().appendLine(localize("warning.file.missing", "Warning: Expected file {0} is missing.", file));
}
}
}
export async function chmodAsync(path: fs.PathLike, mode: fs.Mode): Promise<void> {
return new Promise<void>((resolve, reject) => {
fs.chmod(path, mode, (err: NodeJS.ErrnoException | null) => {
if (err) {
return reject(err);
}
return resolve();
});
});
}
export function removePotentialPII(str: string): string {
const words: string[] = str.split(" ");
let result: string = "";
for (const word of words) {
if (!word.includes(".") && !word.includes("/") && !word.includes("\\") && !word.includes(":")) {
result += word + " ";
} else {
result += "? ";
}
}
return result;
}
export function checkDistro(platformInfo: PlatformInformation): void {
if (platformInfo.platform !== 'win32' && platformInfo.platform !== 'linux' && platformInfo.platform !== 'darwin') {
// this should never happen because VSCode doesn't run on FreeBSD
// or SunOS (the other platforms supported by node)
getOutputChannelLogger().appendLine(localize("warning.debugging.not.tested", "Warning: Debugging has not been tested for this platform.") + " " + getReadmeMessage());
}
}
export async function unlinkAsync(fileName: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
fs.unlink(fileName, err => {
if (err) {
return reject(err);
}
return resolve();
});
});
}
export async function renameAsync(oldName: string, newName: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
fs.rename(oldName, newName, err => {
if (err) {
return reject(err);
}
return resolve();
});
});
}
export async function promptForReloadWindowDueToSettingsChange(): Promise<void> {
await promptReloadWindow(localize("reload.workspace.for.changes", "Reload the workspace for the settings change to take effect."));
}
export async function promptReloadWindow(message: string): Promise<void> {
const reload: string = localize("reload.string", "Reload");
const value: string | undefined = await vscode.window.showInformationMessage(message, reload);
if (value === reload) {
return vscode.commands.executeCommand("workbench.action.reloadWindow");
}
}
export function createTempFileWithPostfix(postfix: string): Promise<tmp.FileResult> {
return new Promise<tmp.FileResult>((resolve, reject) => {
tmp.file({ postfix: postfix }, (err, path, fd, cleanupCallback) => {
if (err) {
return reject(err);
}
return resolve({ name: path, fd: fd, removeCallback: cleanupCallback } as tmp.FileResult);
});
});
}
function resolveWindowsEnvironmentVariables(str: string): string {
return str.replace(/%([^%]+)%/g, (withPercents, withoutPercents) => {
const found: string | undefined = process.env[withoutPercents];
return found || withPercents;
});
}
function legacyExtractArgs(argsString: string): string[] {
const result: string[] = [];
let currentArg: string = "";
let isWithinDoubleQuote: boolean = false;
let isWithinSingleQuote: boolean = false;
for (let i: number = 0; i < argsString.length; i++) {
const c: string = argsString[i];
if (c === '\\') {
currentArg += c;
if (++i === argsString.length) {
if (currentArg !== "") {
result.push(currentArg);
}
return result;
}
currentArg += argsString[i];
continue;
}
if (c === '"') {
if (!isWithinSingleQuote) {
isWithinDoubleQuote = !isWithinDoubleQuote;
}
} else if (c === '\'') {
// On Windows, a single quote string is not allowed to join multiple args into a single arg
if (!isWindows) {
if (!isWithinDoubleQuote) {
isWithinSingleQuote = !isWithinSingleQuote;
}
}
} else if (c === ' ') {
if (!isWithinDoubleQuote && !isWithinSingleQuote) {
if (currentArg !== "") {
result.push(currentArg);
currentArg = "";
}
continue;
}
}
currentArg += c;
}
if (currentArg !== "") {
result.push(currentArg);