-
Notifications
You must be signed in to change notification settings - Fork 511
/
Copy pathplatform.ts
639 lines (526 loc) · 24 KB
/
platform.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import * as os from "os";
import * as path from "path";
import * as process from "process";
import vscode = require("vscode");
import { integer } from "vscode-languageserver-protocol";
import { ILogger } from "./logging";
import { changeSetting, getSettings, PowerShellAdditionalExePathSettings } from "./settings";
import untildify from "untildify";
// This uses require so we can rewire it in unit tests!
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-var-requires
const utils = require("./utils");
const WindowsPowerShell64BitLabel = "Windows PowerShell (x64)";
const WindowsPowerShell32BitLabel = "Windows PowerShell (x86)";
const LinuxExePath = "/usr/bin/pwsh";
const LinuxPreviewExePath = "/usr/bin/pwsh-preview";
const SnapExePath = "/snap/bin/pwsh";
const SnapPreviewExePath = "/snap/bin/pwsh-preview";
const MacOSExePath = "/usr/local/bin/pwsh";
const MacOSPreviewExePath = "/usr/local/bin/pwsh-preview";
const MacOSHomebrewExePath = "/opt/homebrew/bin/pwsh";
const MacOSHomebrewLTSExePath = "/opt/homebrew/bin/pwsh-lts";
const MacOSHomebrewPreviewExePath = "/opt/homebrew/bin/pwsh-preview";
export enum OperatingSystem {
Unknown,
Windows,
MacOS,
Linux,
}
export interface IPlatformDetails {
operatingSystem: OperatingSystem;
isOS64Bit: boolean;
isProcess64Bit: boolean;
}
export interface IPowerShellExeDetails {
readonly displayName: string;
readonly exePath: string;
readonly supportsProperArguments: boolean;
}
export function getPlatformDetails(): IPlatformDetails {
let operatingSystem = OperatingSystem.Unknown;
if (process.platform === "win32") {
operatingSystem = OperatingSystem.Windows;
} else if (process.platform === "darwin") {
operatingSystem = OperatingSystem.MacOS;
} else if (process.platform === "linux") {
operatingSystem = OperatingSystem.Linux;
}
const isProcess64Bit = (process.arch === "x64" || process.arch === "arm64");
return {
operatingSystem,
isOS64Bit: isProcess64Bit || (process.env.PROCESSOR_ARCHITEW6432 !== undefined),
isProcess64Bit,
};
}
/**
* Class to lazily find installed PowerShell executables on a machine.
* When given a list of additional PowerShell executables,
* this will also surface those at the end of the list.
*/
export class PowerShellExeFinder {
// This is required, since parseInt("7-preview") will return 7.
private static IntRegex = /^\d+$/;
private static PwshMsixRegex = /^Microsoft.PowerShell_.*/;
private static PwshPreviewMsixRegex = /^Microsoft.PowerShellPreview_.*/;
private winPS: IPossiblePowerShellExe | undefined;
private alternateBitnessWinPS: IPossiblePowerShellExe | undefined;
/**
* Create a new PowerShellFinder object to discover PowerShell installations.
* @param platformDetails Information about the machine we are running on.
* @param additionalPowerShellExes Additional PowerShell installations as configured in the settings.
*/
constructor(
// The platform details descriptor for the platform we're on
private platformDetails: IPlatformDetails,
// Additional configured PowerShells
private additionalPowerShellExes: PowerShellAdditionalExePathSettings,
private logger: ILogger) { }
/**
* Returns the first available PowerShell executable found in the search order.
*/
public async getFirstAvailablePowerShellInstallation(): Promise<IPowerShellExeDetails | undefined> {
for await (const pwsh of this.enumeratePowerShellInstallations()) {
return pwsh;
}
return undefined;
}
/**
* Get an array of all PowerShell executables found when searching for PowerShell installations.
*/
public async getAllAvailablePowerShellInstallations(): Promise<IPowerShellExeDetails[]> {
const array: IPowerShellExeDetails[] = [];
for await (const pwsh of this.enumeratePowerShellInstallations()) {
array.push(pwsh);
}
return array;
}
/**
* Fixes PowerShell paths when Windows PowerShell is set to the non-native bitness.
* @param configuredPowerShellPath the PowerShell path configured by the user.
*/
public fixWindowsPowerShellPath(configuredPowerShellPath: string): string | undefined {
const altWinPS = this.findWinPS({ useAlternateBitness: true });
if (!altWinPS) {
return configuredPowerShellPath;
}
const lowerAltWinPSPath = altWinPS.exePath.toLocaleLowerCase();
const lowerConfiguredPath = configuredPowerShellPath.toLocaleLowerCase();
if (lowerConfiguredPath === lowerAltWinPSPath) {
return this.findWinPS()?.exePath;
}
return configuredPowerShellPath;
}
/**
* Iterates through PowerShell installations on the machine according
* to configuration passed in through the constructor.
* PowerShell items returned by this object are verified
* to exist on the filesystem.
*/
public async *enumeratePowerShellInstallations(): AsyncIterable<IPowerShellExeDetails> {
// Get the default PowerShell installations first
for await (const defaultPwsh of this.enumerateDefaultPowerShellInstallations()) {
if (defaultPwsh && await defaultPwsh.exists()) {
yield defaultPwsh;
}
}
// Also show any additionally configured PowerShells
// These may be duplicates of the default installations, but given a different name.
for await (const additionalPwsh of this.enumerateAdditionalPowerShellInstallations()) {
if (await additionalPwsh.exists()) {
yield additionalPwsh;
} else if (!additionalPwsh.suppressWarning) {
const message = `Additional PowerShell '${additionalPwsh.displayName}' not found at '${additionalPwsh.exePath}'!`;
this.logger.writeWarning(message);
if (!getSettings().suppressAdditionalExeNotFoundWarning) {
const selection = await vscode.window.showWarningMessage(message, "Don't Show Again");
if (selection !== undefined) {
await changeSetting("suppressAdditionalExeNotFoundWarning", true, true, this.logger);
}
}
}
}
}
/**
* Iterates through all the possible well-known PowerShell installations on a machine.
* Returned values may not exist, but come with an .exists property
* which will check whether the executable exists.
* TODO: We really need to define the order in which we search for stable/LTS/preview/daily
*/
private async *enumerateDefaultPowerShellInstallations(): AsyncIterable<IPossiblePowerShellExe | undefined> {
// Find PSCore stable first
yield this.findPSCoreStable();
switch (this.platformDetails.operatingSystem) {
case OperatingSystem.Linux:
// On Linux, find the snap
yield this.findPSCoreStableSnap();
break;
case OperatingSystem.Windows:
// Windows may have a 32-bit pwsh.exe
yield this.findPSCoreWindowsInstallation({ useAlternateBitness: true });
// Also look for the MSIX/UWP installation
yield await this.findPSCoreMsix();
break;
case OperatingSystem.MacOS:
// On MacOS, find the Homebrew installations
yield this.findPSCoreHomebrewStable();
yield this.findPSCoreHomebrewLTS();
break;
}
// Look for the .NET global tool
// Some older versions of PowerShell have a bug in this where startup will fail,
// but this is fixed in newer versions
yield this.findPSCoreDotnetGlobalTool();
// Look for PSCore preview
yield this.findPSCorePreview();
switch (this.platformDetails.operatingSystem) {
// On Linux, there might be a preview snap
case OperatingSystem.Linux:
yield this.findPSCorePreviewSnap();
break;
case OperatingSystem.Windows:
// Find a preview MSIX
yield this.findPSCoreMsix({ findPreview: true });
// Look for pwsh-preview with the opposite bitness
yield this.findPSCoreWindowsInstallation({ useAlternateBitness: true, findPreview: true });
// Finally, get Windows PowerShell
// Get the natural Windows PowerShell for the process bitness
yield this.findWinPS();
// Get the alternate bitness Windows PowerShell
yield this.findWinPS({ useAlternateBitness: true });
break;
case OperatingSystem.MacOS:
// On MacOS, find the Homebrew preview
yield this.findPSCoreHomebrewPreview();
break;
}
// Look for PSCore daily
yield this.findPSCoreDaily();
}
/**
* Iterates through the configured additional PowerShell executable locations,
* without checking for their existence.
*/
private async *enumerateAdditionalPowerShellInstallations(): AsyncIterable<IPossiblePowerShellExe> {
for (const versionName in this.additionalPowerShellExes) {
if (Object.prototype.hasOwnProperty.call(this.additionalPowerShellExes, versionName)) {
let exePath: string | undefined = utils.stripQuotePair(this.additionalPowerShellExes[versionName]);
if (!exePath) {
continue;
}
exePath = untildify(exePath);
const args: [string, undefined, boolean, boolean]
// Must be a tuple type and is suppressing the warning
= [versionName, undefined, true, true];
// Always search for what the user gave us first, but with the warning
// suppressed so we can display it after all possibilities are exhausted
let pwsh = new PossiblePowerShellExe(exePath, ...args);
if (await pwsh.exists()) {
yield pwsh;
continue;
}
// Also search for `pwsh[.exe]` and `powershell[.exe]` if missing
if (this.platformDetails.operatingSystem === OperatingSystem.Windows) {
// Handle Windows where '.exe' and 'powershell' are things
if (!exePath.endsWith("pwsh.exe") && !exePath.endsWith("powershell.exe")) {
if (exePath.endsWith("pwsh") || exePath.endsWith("powershell")) {
// Add extension if that was missing
pwsh = new PossiblePowerShellExe(exePath + ".exe", ...args);
if (await pwsh.exists()) {
yield pwsh;
continue;
}
}
// Also add full exe names (this isn't an else just in case
// the folder was named "pwsh" or "powershell")
pwsh = new PossiblePowerShellExe(path.join(exePath, "pwsh.exe"), ...args);
if (await pwsh.exists()) {
yield pwsh;
continue;
}
pwsh = new PossiblePowerShellExe(path.join(exePath, "powershell.exe"), ...args);
if (await pwsh.exists()) {
yield pwsh;
continue;
}
}
} else if (!exePath.endsWith("pwsh")) {
// Always just 'pwsh' on non-Windows
pwsh = new PossiblePowerShellExe(path.join(exePath, "pwsh"), ...args);
if (await pwsh.exists()) {
yield pwsh;
continue;
}
}
// If we're still being iterated over, no permutation of the given path existed so yield an object with the warning unsuppressed
yield new PossiblePowerShellExe(exePath, versionName, false, undefined, false);
}
}
}
private async findPSCoreStable(): Promise<IPossiblePowerShellExe | undefined> {
switch (this.platformDetails.operatingSystem) {
case OperatingSystem.Linux:
return new PossiblePowerShellExe(LinuxExePath, "PowerShell");
case OperatingSystem.MacOS:
return new PossiblePowerShellExe(MacOSExePath, "PowerShell");
case OperatingSystem.Windows:
return await this.findPSCoreWindowsInstallation();
case OperatingSystem.Unknown:
return undefined;
}
}
private async findPSCorePreview(): Promise<IPossiblePowerShellExe | undefined> {
switch (this.platformDetails.operatingSystem) {
case OperatingSystem.Linux:
return new PossiblePowerShellExe(LinuxPreviewExePath, "PowerShell Preview");
case OperatingSystem.MacOS:
return new PossiblePowerShellExe(MacOSPreviewExePath, "PowerShell Preview");
case OperatingSystem.Windows:
return await this.findPSCoreWindowsInstallation({ findPreview: true });
case OperatingSystem.Unknown:
return undefined;
}
}
/**
* If the daily was installed via 'https://aka.ms/install-powershell.ps1', then
* this is the default installation location:
*
* if ($IsWinEnv) {
* $Destination = "$env:LOCALAPPDATA\Microsoft\powershell"
* } else {
* $Destination = "~/.powershell"
* }
*
* if ($Daily) {
* $Destination = "${Destination}-daily"
* }
*
* TODO: Remove this after the daily is officially no longer supported.
*/
private findPSCoreDaily(): IPossiblePowerShellExe | undefined {
switch (this.platformDetails.operatingSystem) {
case OperatingSystem.Linux:
case OperatingSystem.MacOS: {
const exePath = path.join(os.homedir(), ".powershell-daily", "pwsh");
return new PossiblePowerShellExe(exePath, "PowerShell Daily");
}
case OperatingSystem.Windows: {
// We can't proceed if there's no LOCALAPPDATA path
if (!process.env.LOCALAPPDATA) {
return undefined;
}
const exePath = path.join(process.env.LOCALAPPDATA, "Microsoft", "powershell-daily", "pwsh.exe");
return new PossiblePowerShellExe(exePath, "PowerShell Daily");
}
case OperatingSystem.Unknown:
return undefined;
}
}
// The Homebrew installations of PowerShell on Apple Silicon are no longer in the default PATH.
private findPSCoreHomebrewStable(): IPossiblePowerShellExe {
return new PossiblePowerShellExe(MacOSHomebrewExePath, "PowerShell (Homebrew)");
}
private findPSCoreHomebrewLTS(): IPossiblePowerShellExe {
return new PossiblePowerShellExe(MacOSHomebrewLTSExePath, "PowerShell LTS (Homebrew)");
}
private findPSCoreHomebrewPreview(): IPossiblePowerShellExe {
return new PossiblePowerShellExe(MacOSHomebrewPreviewExePath, "PowerShell Preview (Homebrew)");
}
private findPSCoreDotnetGlobalTool(): IPossiblePowerShellExe {
const exeName: string = this.platformDetails.operatingSystem === OperatingSystem.Windows
? "pwsh.exe"
: "pwsh";
const dotnetGlobalToolExePath: string = path.join(os.homedir(), ".dotnet", "tools", exeName);
// The dotnet installed version of PowerShell does not support proper argument parsing, and so it fails with our multi-line startup banner.
return new PossiblePowerShellExe(dotnetGlobalToolExePath, ".NET Core PowerShell Global Tool", undefined, false);
}
private async findPSCoreMsix({ findPreview }: { findPreview?: boolean } = {}): Promise<IPossiblePowerShellExe | undefined> {
// We can't proceed if there's no LOCALAPPDATA path
if (!process.env.LOCALAPPDATA) {
return undefined;
}
// Find the base directory for MSIX application exe shortcuts
const msixAppDir = path.join(process.env.LOCALAPPDATA, "Microsoft", "WindowsApps");
if (!await utils.checkIfDirectoryExists(msixAppDir)) {
return undefined;
}
// Define whether we're looking for the preview or the stable
const { pwshMsixDirRegex, pwshMsixName } = findPreview
? { pwshMsixDirRegex: PowerShellExeFinder.PwshPreviewMsixRegex, pwshMsixName: "PowerShell Preview (Store)" }
: { pwshMsixDirRegex: PowerShellExeFinder.PwshMsixRegex, pwshMsixName: "PowerShell (Store)" };
// We should find only one such application, so return on the first one
for (const name of await utils.readDirectory(msixAppDir)) {
if (pwshMsixDirRegex.test(name)) {
return new PossiblePowerShellExe(path.join(msixAppDir, name, "pwsh.exe"), pwshMsixName);
}
}
return undefined;
}
// TODO: Are snaps still a thing?
private findPSCoreStableSnap(): IPossiblePowerShellExe {
return new PossiblePowerShellExe(SnapExePath, "PowerShell Snap");
}
private findPSCorePreviewSnap(): IPossiblePowerShellExe {
return new PossiblePowerShellExe(SnapPreviewExePath, "PowerShell Preview Snap");
}
private async findPSCoreWindowsInstallation(
{ useAlternateBitness = false, findPreview = false }:
{ useAlternateBitness?: boolean; findPreview?: boolean } = {}): Promise<IPossiblePowerShellExe | undefined> {
const programFilesPath = this.getProgramFilesPath({ useAlternateBitness });
if (!programFilesPath) {
return undefined;
}
const powerShellInstallBaseDir = path.join(programFilesPath, "PowerShell");
// Ensure the base directory exists
if (!await utils.checkIfDirectoryExists(powerShellInstallBaseDir)) {
return undefined;
}
let highestSeenVersion = -1;
let pwshExePath: string | undefined;
for (const item of await utils.readDirectory(powerShellInstallBaseDir)) {
let currentVersion = -1;
if (findPreview) {
// We are looking for something like "7-preview"
// Preview dirs all have dashes in them
const dashIndex: integer = item.indexOf("-");
if (dashIndex < 0) {
continue;
}
// Verify that the part before the dash is an integer
const intPart: string = item.substring(0, dashIndex);
if (!PowerShellExeFinder.IntRegex.test(intPart)) {
continue;
}
// Verify that the part after the dash is "preview"
if (item.substring(dashIndex + 1) !== "preview") {
continue;
}
currentVersion = parseInt(intPart, 10);
} else {
// Search for a directory like "6" or "7"
if (!PowerShellExeFinder.IntRegex.test(item)) {
continue;
}
currentVersion = parseInt(item, 10);
}
// Ensure we haven't already seen a higher version
if (currentVersion <= highestSeenVersion) {
continue;
}
// Now look for the file
const exePath = path.join(powerShellInstallBaseDir, item, "pwsh.exe");
if (!await utils.checkIfFileExists(exePath)) {
continue;
}
pwshExePath = exePath;
highestSeenVersion = currentVersion;
}
if (!pwshExePath) {
return undefined;
}
const bitness: string = programFilesPath.includes("x86")
? "(x86)"
: "(x64)";
const preview: string = findPreview ? " Preview" : "";
return new PossiblePowerShellExe(pwshExePath, `PowerShell${preview} ${bitness}`);
}
private findWinPS({ useAlternateBitness = false }: { useAlternateBitness?: boolean } = {}): IPossiblePowerShellExe | undefined {
// 32-bit OSes only have one WinPS on them
if (!this.platformDetails.isOS64Bit && useAlternateBitness) {
return undefined;
}
let winPS = useAlternateBitness ? this.alternateBitnessWinPS : this.winPS;
if (winPS === undefined) {
const systemFolderPath = this.getSystem32Path({ useAlternateBitness });
if (!systemFolderPath) {
return undefined;
}
const winPSPath = path.join(systemFolderPath, "WindowsPowerShell", "v1.0", "powershell.exe");
let displayName: string;
if (this.platformDetails.isProcess64Bit) {
displayName = useAlternateBitness
? WindowsPowerShell32BitLabel
: WindowsPowerShell64BitLabel;
} else if (this.platformDetails.isOS64Bit) {
displayName = useAlternateBitness
? WindowsPowerShell64BitLabel
: WindowsPowerShell32BitLabel;
} else {
displayName = WindowsPowerShell32BitLabel;
}
winPS = new PossiblePowerShellExe(winPSPath, displayName, true);
if (useAlternateBitness) {
this.alternateBitnessWinPS = winPS;
} else {
this.winPS = winPS;
}
}
return winPS;
}
private getProgramFilesPath(
{ useAlternateBitness = false }: { useAlternateBitness?: boolean } = {}): string | undefined {
if (!useAlternateBitness) {
// Just use the native system bitness
return process.env.ProgramFiles;
}
// We might be a 64-bit process looking for 32-bit program files
if (this.platformDetails.isProcess64Bit) {
return process.env["ProgramFiles(x86)"];
}
// We might be a 32-bit process looking for 64-bit program files
if (this.platformDetails.isOS64Bit) {
return process.env.ProgramW6432;
}
// We're a 32-bit process on 32-bit Windows, there is no other Program Files dir
return undefined;
}
private getSystem32Path({ useAlternateBitness = false }: { useAlternateBitness?: boolean } = {}): string | undefined {
const windir = process.env.windir;
if (!windir) {
return undefined;
}
if (!useAlternateBitness) {
// Just use the native system bitness
return path.join(windir, "System32");
}
// We might be a 64-bit process looking for 32-bit system32
if (this.platformDetails.isProcess64Bit) {
return path.join(windir, "SysWOW64");
}
// We might be a 32-bit process looking for 64-bit system32
if (this.platformDetails.isOS64Bit) {
return path.join(windir, "Sysnative");
}
// We're on a 32-bit Windows, so no alternate bitness
return undefined;
}
}
export function getWindowsSystemPowerShellPath(systemFolderName: string): string | undefined {
if (process.env.windir === undefined) {
return undefined;
} else return path.join(
process.env.windir,
systemFolderName,
"WindowsPowerShell",
"v1.0",
"powershell.exe");
}
interface IPossiblePowerShellExe extends IPowerShellExeDetails {
exists(): Promise<boolean>;
readonly suppressWarning: boolean;
}
class PossiblePowerShellExe implements IPossiblePowerShellExe {
constructor(
public readonly exePath: string,
public readonly displayName: string,
private knownToExist?: boolean,
public readonly supportsProperArguments = true,
public readonly suppressWarning = false) { }
public async exists(): Promise<boolean> {
if (this.knownToExist === undefined) {
this.knownToExist = await utils.checkIfFileExists(this.exePath);
}
return this.knownToExist ?? false;
}
}