-
Notifications
You must be signed in to change notification settings - Fork 511
/
Copy pathsession.ts
829 lines (691 loc) · 32.3 KB
/
session.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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import os = require('os');
import fs = require('fs');
import net = require('net');
import path = require('path');
import utils = require('./utils');
import vscode = require('vscode');
import cp = require('child_process');
import Settings = require('./settings');
import { Logger } from './logging';
import { IFeature } from './feature';
import { Message } from 'vscode-jsonrpc';
import { StringDecoder } from 'string_decoder';
import { LanguageClient, LanguageClientOptions, Executable, RequestType, RequestType0, NotificationType, StreamInfo, ErrorAction, CloseAction } from 'vscode-languageclient';
export enum SessionStatus {
NotStarted,
Initializing,
Running,
Stopping,
Failed
}
enum SessionType {
UseDefault,
UseCurrent,
UsePath,
UseBuiltIn
}
interface DefaultSessionConfiguration {
type: SessionType.UseDefault
}
interface CurrentSessionConfiguration {
type: SessionType.UseCurrent,
}
interface PathSessionConfiguration {
type: SessionType.UsePath,
path: string;
isWindowsDevBuild: boolean;
}
interface BuiltInSessionConfiguration {
type: SessionType.UseBuiltIn;
path?: string;
is32Bit: boolean;
}
type SessionConfiguration =
DefaultSessionConfiguration |
CurrentSessionConfiguration |
PathSessionConfiguration |
BuiltInSessionConfiguration;
export class SessionManager {
private ShowSessionMenuCommandName = "PowerShell.ShowSessionMenu";
private hostVersion: string;
private isWindowsOS: boolean;
private sessionFilePath: string;
private sessionStatus: SessionStatus;
private focusConsoleOnExecute: boolean;
private extensionFeatures: IFeature[] = [];
private statusBarItem: vscode.StatusBarItem;
private sessionConfiguration: SessionConfiguration;
private versionDetails: PowerShellVersionDetails;
private registeredCommands: vscode.Disposable[] = [];
private consoleTerminal: vscode.Terminal = undefined;
private languageServerClient: LanguageClient = undefined;
private sessionSettings: Settings.ISettings = undefined;
private sessionDetails: utils.EditorServicesSessionDetails;
// When in development mode, VS Code's session ID is a fake
// value of "someValue.machineId". Use that to detect dev
// mode for now until Microsoft/vscode#10272 gets implemented.
private readonly inDevelopmentMode =
vscode.env.sessionId === "someValue.sessionId";
constructor(
private requiredEditorServicesVersion: string,
private log: Logger) {
this.isWindowsOS = os.platform() == "win32";
// Get the current version of this extension
this.hostVersion =
vscode
.extensions
.getExtension("ms-vscode.PowerShell")
.packageJSON
.version;
// Fix the host version so that PowerShell can consume it.
// This is needed when the extension uses a prerelease
// version string like 0.9.1-insiders-1234.
this.hostVersion = this.hostVersion.split('-')[0];
this.registerCommands();
}
public setExtensionFeatures(extensionFeatures: IFeature[]) {
this.extensionFeatures = extensionFeatures;
}
public start(sessionConfig: SessionConfiguration = { type: SessionType.UseDefault }) {
this.sessionSettings = Settings.load(utils.PowerShellLanguageId);
this.log.startNewLog(this.sessionSettings.developer.editorServicesLogLevel);
this.focusConsoleOnExecute = this.sessionSettings.integratedConsole.focusConsoleOnExecute;
this.createStatusBarItem();
this.sessionFilePath =
utils.getSessionFilePath(
Math.floor(100000 + Math.random() * 900000));
this.sessionConfiguration = this.resolveSessionConfiguration(sessionConfig);
if (this.sessionConfiguration.type === SessionType.UsePath ||
this.sessionConfiguration.type === SessionType.UseBuiltIn) {
var bundledModulesPath = path.resolve(__dirname, "../modules");
if (this.inDevelopmentMode) {
var devBundledModulesPath =
// this.sessionSettings.developer.bundledModulesPath ||
path.resolve(
__dirname,
this.sessionSettings.developer.bundledModulesPath ||
"../../PowerShellEditorServices/module");
// Make sure the module's bin path exists
if (fs.existsSync(path.join(devBundledModulesPath, "PowerShellEditorServices/bin"))) {
bundledModulesPath = devBundledModulesPath;
}
else {
this.log.write(
`\nWARNING: In development mode but PowerShellEditorServices dev module path cannot be found (or has not been built yet): ${devBundledModulesPath}\n`);
}
}
var startArgs =
"-EditorServicesVersion '" + this.requiredEditorServicesVersion + "' " +
"-HostName 'Visual Studio Code Host' " +
"-HostProfileId 'Microsoft.VSCode' " +
"-HostVersion '" + this.hostVersion + "' " +
"-BundledModulesPath '" + bundledModulesPath + "' " +
"-EnableConsoleRepl ";
if (this.sessionSettings.developer.editorServicesWaitForDebugger) {
startArgs += '-WaitForDebugger ';
}
if (this.sessionSettings.developer.editorServicesLogLevel) {
startArgs += "-LogLevel '" + this.sessionSettings.developer.editorServicesLogLevel + "' "
}
var isWindowsDevBuild =
this.sessionConfiguration.type == SessionType.UsePath
? this.sessionConfiguration.isWindowsDevBuild : false;
this.startPowerShell(
this.sessionConfiguration.path,
isWindowsDevBuild,
bundledModulesPath,
startArgs);
}
else {
this.setSessionFailure("PowerShell could not be started, click 'Show Logs' for more details.");
}
}
public stop() {
// Shut down existing session if there is one
this.log.write(os.EOL + os.EOL + "Shutting down language client...");
if (this.sessionStatus === SessionStatus.Failed) {
// Before moving further, clear out the client and process if
// the process is already dead (i.e. it crashed)
this.languageServerClient = undefined;
this.consoleTerminal = undefined;
}
this.sessionStatus = SessionStatus.Stopping;
// Close the language server client
if (this.languageServerClient !== undefined) {
this.languageServerClient.stop();
this.languageServerClient = undefined;
}
// Clean up the session file
utils.deleteSessionFile(this.sessionFilePath);
// Kill the PowerShell process we spawned via the console
if (this.consoleTerminal !== undefined) {
this.log.write(os.EOL + "Terminating PowerShell process...");
this.consoleTerminal.dispose();
this.consoleTerminal = undefined;
}
this.sessionStatus = SessionStatus.NotStarted;
}
public getSessionDetails(): utils.EditorServicesSessionDetails {
return this.sessionDetails;
}
public dispose() : void {
// Stop the current session
this.stop();
// Dispose of all commands
this.registeredCommands.forEach(command => { command.dispose(); });
}
private onConfigurationUpdated() {
var settings = Settings.load(utils.PowerShellLanguageId);
this.focusConsoleOnExecute = settings.integratedConsole.focusConsoleOnExecute;
// Detect any setting changes that would affect the session
if (settings.useX86Host !== this.sessionSettings.useX86Host ||
settings.developer.powerShellExePath.toLowerCase() !== this.sessionSettings.developer.powerShellExePath.toLowerCase() ||
settings.developer.editorServicesLogLevel.toLowerCase() !== this.sessionSettings.developer.editorServicesLogLevel.toLowerCase() ||
settings.developer.bundledModulesPath.toLowerCase() !== this.sessionSettings.developer.bundledModulesPath.toLowerCase()) {
vscode.window.showInformationMessage(
"The PowerShell runtime configuration has changed, would you like to start a new session?",
"Yes", "No")
.then((response) => {
if (response === "Yes") {
this.restartSession({ type: SessionType.UseDefault })
}
});
}
}
private setStatusBarVersionString(
runspaceDetails: RunspaceDetails) {
var versionString =
this.versionDetails.architecture === "x86"
? `${runspaceDetails.powerShellVersion.displayVersion} (${runspaceDetails.powerShellVersion.architecture})`
: runspaceDetails.powerShellVersion.displayVersion;
if (runspaceDetails.runspaceType != RunspaceType.Local) {
versionString += ` [${runspaceDetails.connectionString}]`
}
this.setSessionStatus(
versionString,
SessionStatus.Running);
}
private registerCommands() : void {
this.registeredCommands = [
vscode.commands.registerCommand('PowerShell.RestartSession', () => { this.restartSession(); }),
vscode.commands.registerCommand(this.ShowSessionMenuCommandName, () => { this.showSessionMenu(); }),
vscode.workspace.onDidChangeConfiguration(() => this.onConfigurationUpdated()),
vscode.commands.registerCommand('PowerShell.ShowSessionConsole', (isExecute?: boolean) => { this.showSessionConsole(isExecute); })
]
}
private startPowerShell(
powerShellExePath: string,
isWindowsDevBuild: boolean,
bundledModulesPath: string,
startArgs: string) {
try
{
this.setSessionStatus(
"Starting PowerShell...",
SessionStatus.Initializing);
let startScriptPath =
path.resolve(
__dirname,
'../scripts/Start-EditorServices.ps1');
var editorServicesLogPath = this.log.getLogFilePath("EditorServices");
var featureFlags =
this.sessionSettings.developer.featureFlags !== undefined
? this.sessionSettings.developer.featureFlags.map(f => `'${f}'`).join(', ')
: "";
startArgs +=
`-LogPath '${editorServicesLogPath}' ` +
`-SessionDetailsPath '${this.sessionFilePath}' ` +
`-FeatureFlags @(${featureFlags})`
var powerShellArgs = [
"-NoProfile",
"-NonInteractive"
]
// Only add ExecutionPolicy param on Windows
if (this.isWindowsOS) {
powerShellArgs.push("-ExecutionPolicy", "Unrestricted")
}
powerShellArgs.push(
"-Command",
"& '" + startScriptPath + "' " + startArgs);
if (isWindowsDevBuild) {
// Windows PowerShell development builds need the DEVPATH environment
// variable set to the folder where development binaries are held
// NOTE: This batch file approach is needed temporarily until VS Code's
// createTerminal API gets an argument for setting environment variables
// on the launched process.
var batScriptPath = path.resolve(__dirname, '../sessions/powershell.bat');
fs.writeFileSync(
batScriptPath,
`@set DEVPATH=${path.dirname(powerShellExePath)}\r\n@${powerShellExePath} %*`);
powerShellExePath = batScriptPath;
}
this.log.write(`${utils.getTimestampString()} Language server starting...`);
// Make sure no old session file exists
utils.deleteSessionFile(this.sessionFilePath);
// Launch PowerShell in the integrated terminal
this.consoleTerminal =
vscode.window.createTerminal(
"PowerShell Integrated Console",
powerShellExePath,
powerShellArgs);
if (this.sessionSettings.integratedConsole.showOnStartup) {
this.consoleTerminal.show(true);
}
// Start the language client
utils.waitForSessionFile(
this.sessionFilePath,
(sessionDetails, error) => {
this.sessionDetails = sessionDetails;
if (sessionDetails) {
if (sessionDetails.status === "started") {
this.log.write(`${utils.getTimestampString()} Language server started.`);
// The session file is no longer needed
utils.deleteSessionFile(this.sessionFilePath);
// Start the language service client
this.startLanguageClient(sessionDetails);
}
else if (sessionDetails.status === "failed") {
if (sessionDetails.reason === "unsupported") {
this.setSessionFailure(
`PowerShell language features are only supported on PowerShell version 3 and above. The current version is ${sessionDetails.powerShellVersion}.`)
}
else if (sessionDetails.reason === "languageMode") {
this.setSessionFailure(
`PowerShell language features are disabled due to an unsupported LanguageMode: ${sessionDetails.detail}`);
}
else {
this.setSessionFailure(`PowerShell could not be started for an unknown reason '${sessionDetails.reason}'`)
}
}
else {
// TODO: Handle other response cases
}
}
else {
this.log.write(`${utils.getTimestampString()} Language server startup failed.`);
this.setSessionFailure("Could not start language service: ", error);
}
});
// this.powerShellProcess.stderr.on(
// 'data',
// (data) => {
// this.log.writeError("ERROR: " + data);
// if (this.sessionStatus === SessionStatus.Initializing) {
// this.setSessionFailure("PowerShell could not be started, click 'Show Logs' for more details.");
// }
// else if (this.sessionStatus === SessionStatus.Running) {
// this.promptForRestart();
// }
// });
vscode.window.onDidCloseTerminal(
terminal => {
if (terminal === this.consoleTerminal) {
this.log.write(os.EOL + "powershell.exe terminated or terminal UI was closed" + os.EOL);
if (this.sessionStatus === SessionStatus.Running) {
this.setSessionStatus("Session exited", SessionStatus.Failed);
this.promptForRestart();
}
}
});
this.consoleTerminal.processId.then(
pid => {
console.log("powershell.exe started, pid: " + pid + ", exe: " + powerShellExePath);
this.log.write(
"powershell.exe started --",
" pid: " + pid,
" exe: " + powerShellExePath,
" args: " + startScriptPath + ' ' + startArgs + os.EOL + os.EOL);
});
}
catch (e)
{
this.setSessionFailure("The language service could not be started: ", e);
}
}
private promptForRestart() {
vscode.window.showErrorMessage(
"The PowerShell session has terminated due to an error, would you like to restart it?",
"Yes", "No")
.then((answer) => { if (answer === "Yes") { this.restartSession(); }});
}
private startLanguageClient(sessionDetails: utils.EditorServicesSessionDetails) {
var port = sessionDetails.languageServicePort;
// Log the session details object
this.log.write(JSON.stringify(sessionDetails));
try
{
this.log.write("Connecting to language service on port " + port + "..." + os.EOL);
let connectFunc = () => {
return new Promise<StreamInfo>(
(resolve, reject) => {
var socket = net.connect(port);
socket.on(
'connect',
() => {
this.log.write("Language service connected.");
resolve({writer: socket, reader: socket})
});
});
};
let clientOptions: LanguageClientOptions = {
documentSelector: [utils.PowerShellLanguageId],
synchronize: {
configurationSection: utils.PowerShellLanguageId,
//fileEvents: vscode.workspace.createFileSystemWatcher('**/.eslintrc')
},
errorHandler: {
// Override the default error handler to prevent it from
// closing the LanguageClient incorrectly when the socket
// hangs up (ECONNRESET errors).
error: (error: any, message: Message, count: number): ErrorAction => {
// TODO: Is there any error worth terminating on?
return ErrorAction.Continue;
},
closed: () => {
// We have our own restart experience
return CloseAction.DoNotRestart
}
}
}
this.languageServerClient =
new LanguageClient(
'PowerShell Editor Services',
connectFunc,
clientOptions);
this.languageServerClient.onReady().then(
() => {
this.languageServerClient
.sendRequest(PowerShellVersionRequest.type)
.then(
(versionDetails) => {
this.versionDetails = versionDetails;
this.setSessionStatus(
this.versionDetails.architecture === "x86"
? `${this.versionDetails.displayVersion} (${this.versionDetails.architecture})`
: this.versionDetails.displayVersion,
SessionStatus.Running);
});
// Send the new LanguageClient to extension features
// so that they can register their message handlers
// before the connection is established.
this.updateExtensionFeatures(this.languageServerClient);
this.languageServerClient.onNotification(
RunspaceChangedEvent.type,
(runspaceDetails) => { this.setStatusBarVersionString(runspaceDetails); });
},
(reason) => {
this.setSessionFailure("Could not start language service: ", reason);
});
this.languageServerClient.start();
}
catch (e)
{
this.setSessionFailure("The language service could not be started: ", e);
}
}
private updateExtensionFeatures(languageClient: LanguageClient) {
this.extensionFeatures.forEach(feature => {
feature.setLanguageClient(languageClient);
});
}
private restartSession(sessionConfig?: SessionConfiguration) {
this.stop();
this.start(sessionConfig);
}
private createStatusBarItem() {
if (this.statusBarItem === undefined) {
// Create the status bar item and place it right next
// to the language indicator
this.statusBarItem =
vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
1);
this.statusBarItem.command = this.ShowSessionMenuCommandName;
this.statusBarItem.show();
vscode.window.onDidChangeActiveTextEditor(textEditor => {
if (textEditor === undefined
|| textEditor.document.languageId !== "powershell") {
this.statusBarItem.hide();
}
else {
this.statusBarItem.show();
}
})
}
}
private setSessionStatus(statusText: string, status: SessionStatus): void {
// Set color and icon for 'Running' by default
var statusIconText = "$(terminal) ";
var statusColor = "#affc74";
if (status == SessionStatus.Initializing) {
statusIconText = "$(sync) ";
statusColor = "#f3fc74";
}
else if (status == SessionStatus.Failed) {
statusIconText = "$(alert) ";
statusColor = "#fcc174";
}
this.sessionStatus = status;
this.statusBarItem.color = statusColor;
this.statusBarItem.text = statusIconText + statusText;
}
private setSessionFailure(message: string, ...additionalMessages: string[]) {
this.log.writeAndShowError(message, ...additionalMessages);
this.setSessionStatus(
"Initialization Error",
SessionStatus.Failed);
}
private resolveSessionConfiguration(sessionConfig: SessionConfiguration): SessionConfiguration {
switch (sessionConfig.type) {
case SessionType.UseCurrent: return this.sessionConfiguration;
case SessionType.UseDefault:
// Is there a setting override for the PowerShell path?
var powerShellExePath = (this.sessionSettings.developer.powerShellExePath || "").trim();
if (powerShellExePath.length > 0) {
return this.resolveSessionConfiguration(
{ type: SessionType.UsePath,
path: this.sessionSettings.developer.powerShellExePath,
isWindowsDevBuild: this.sessionSettings.developer.powerShellExeIsWindowsDevBuild});
}
else {
return this.resolveSessionConfiguration(
{ type: SessionType.UseBuiltIn, is32Bit: this.sessionSettings.useX86Host });
}
case SessionType.UsePath:
sessionConfig.path = this.resolvePowerShellPath(sessionConfig.path);
return sessionConfig;
case SessionType.UseBuiltIn:
sessionConfig.path = this.getBuiltInPowerShellPath(sessionConfig.is32Bit);
return sessionConfig;
}
}
private getPowerShellCorePaths(): string[] {
var paths: string[] = [];
if (this.isWindowsOS) {
const is64Bit = process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
const rootInstallPath = (is64Bit ? process.env.ProgramW6432 : process.env.ProgramFiles) + '\\PowerShell';
if (fs.existsSync(rootInstallPath)) {
var dirs =
fs.readdirSync(rootInstallPath)
.map(item => path.join(rootInstallPath, item))
.filter(item => fs.lstatSync(item).isDirectory());
if (dirs) {
paths = paths.concat(dirs);
}
}
}
return paths;
}
private getBuiltInPowerShellPath(use32Bit: boolean): string | null {
// Find the path to powershell.exe based on the current platform
// and the user's desire to run the x86 version of PowerShell
var powerShellExePath = undefined;
if (this.isWindowsOS) {
powerShellExePath =
use32Bit || !process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432')
? process.env.windir + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
: process.env.windir + '\\Sysnative\\WindowsPowerShell\\v1.0\\powershell.exe';
}
else if (os.platform() == "darwin") {
powerShellExePath = "/usr/local/bin/powershell";
// Check for OpenSSL dependency on macOS. Look for the default Homebrew installation
// path and if that fails check the system-wide library path.
if (!(utils.checkIfFileExists("/usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib") &&
utils.checkIfFileExists("/usr/local/opt/openssl/lib/libssl.1.0.0.dylib")) &&
!(utils.checkIfFileExists("/usr/local/lib/libcrypto.1.0.0.dylib") &&
utils.checkIfFileExists("/usr/local/lib/libssl.1.0.0.dylib"))) {
var thenable =
vscode.window.showWarningMessage(
"The PowerShell extension will not work without OpenSSL on macOS and OS X",
"Show Documentation");
thenable.then(
(s) => {
if (s === "Show Documentation") {
cp.exec("open https://github.com/PowerShell/vscode-powershell/blob/master/docs/troubleshooting.md#1-powershell-intellisense-does-not-work-cant-debug-scripts");
}
});
// Don't continue initializing since Editor Services will not load successfully
this.setSessionFailure("Cannot start PowerShell Editor Services due to missing OpenSSL dependency.");
return null;
}
}
else {
powerShellExePath = "/usr/bin/powershell";
}
return this.resolvePowerShellPath(powerShellExePath);
}
private resolvePowerShellPath(powerShellExePath: string): string {
var resolvedPath = path.resolve(__dirname, powerShellExePath);
// If the path does not exist, show an error
if (!utils.checkIfFileExists(resolvedPath)) {
this.setSessionFailure(
"powershell.exe cannot be found or is not accessible at path " + resolvedPath);
return null;
}
return resolvedPath;
}
private showSessionConsole(isExecute?: boolean) {
if (this.consoleTerminal) {
this.consoleTerminal.show(
isExecute && !this.focusConsoleOnExecute);
}
}
private showSessionMenu() {
var menuItems: SessionMenuItem[] = [];
if (this.sessionStatus === SessionStatus.Initializing ||
this.sessionStatus === SessionStatus.NotStarted ||
this.sessionStatus === SessionStatus.Stopping) {
// Don't show a menu for these states
return;
}
if (this.sessionStatus === SessionStatus.Running) {
menuItems = [
new SessionMenuItem(
`Current session: PowerShell ${this.versionDetails.displayVersion} (${this.versionDetails.architecture}) ${this.versionDetails.edition} Edition [${this.versionDetails.version}]`,
() => { vscode.commands.executeCommand("PowerShell.ShowLogs"); }),
new SessionMenuItem(
"Restart Current Session",
() => { this.restartSession(); }),
];
}
else if (this.sessionStatus === SessionStatus.Failed) {
menuItems = [
new SessionMenuItem(
`Session initialization failed, click here to show PowerShell extension logs`,
() => { vscode.commands.executeCommand("PowerShell.ShowLogs"); }),
];
}
if (this.isWindowsOS) {
var item32 =
new SessionMenuItem(
"Switch to Windows PowerShell (x86)",
() => { this.restartSession({ type: SessionType.UseBuiltIn, is32Bit: true}) });
var item64 =
new SessionMenuItem(
"Switch to Windows PowerShell (x64)",
() => { this.restartSession({ type: SessionType.UseBuiltIn, is32Bit: false }) });
var pscorePaths = this.getPowerShellCorePaths();
for (var pscorePath of pscorePaths) {
var pscoreVersion = path.parse(pscorePath).base;
var pscoreExePath = path.join(pscorePath, "powershell.exe");
var pscoreItem = new SessionMenuItem(
`Switch to PowerShell Core ${pscoreVersion}`,
() => { this.restartSession({
type: SessionType.UsePath, path: pscoreExePath, isWindowsDevBuild: false })
});
menuItems.push(pscoreItem);
}
// If the configured PowerShell path isn't being used, offer it as an option
if (this.sessionSettings.developer.powerShellExePath !== "" &&
(this.sessionConfiguration.type !== SessionType.UsePath ||
this.sessionConfiguration.path !== this.sessionSettings.developer.powerShellExePath)) {
menuItems.push(
new SessionMenuItem(
`Switch to PowerShell at path: ${this.sessionSettings.developer.powerShellExePath}`,
() => {
this.restartSession(
{ type: SessionType.UsePath,
path: this.sessionSettings.developer.powerShellExePath,
isWindowsDevBuild: this.sessionSettings.developer.powerShellExeIsWindowsDevBuild })
}));
}
if (this.sessionConfiguration.type === SessionType.UseBuiltIn) {
menuItems.push(
this.sessionConfiguration.is32Bit ? item64 : item32);
}
else {
menuItems.push(item32);
menuItems.push(item64);
}
}
else {
if (this.sessionConfiguration.type !== SessionType.UseBuiltIn) {
menuItems.push(
new SessionMenuItem(
"Use built-in PowerShell",
() => { this.restartSession({ type: SessionType.UseBuiltIn, is32Bit: false }) }));
}
}
menuItems.push(
new SessionMenuItem(
"Open Session Logs Folder",
() => { vscode.commands.executeCommand("PowerShell.OpenLogFolder"); }));
vscode
.window
.showQuickPick<SessionMenuItem>(menuItems)
.then((selectedItem) => { selectedItem.callback(); });
}
}
class SessionMenuItem implements vscode.QuickPickItem {
public description: string;
constructor(
public readonly label: string,
public readonly callback: () => void = () => { })
{
}
}
export namespace PowerShellVersionRequest {
export const type = new RequestType0<PowerShellVersionDetails, void, void>('powerShell/getVersion');
}
export interface PowerShellVersionDetails {
version: string;
displayVersion: string;
edition: string;
architecture: string;
}
export enum RunspaceType {
Local,
Process,
Remote
}
export interface RunspaceDetails {
powerShellVersion: PowerShellVersionDetails;
runspaceType: RunspaceType;
connectionString: string;
}
export namespace RunspaceChangedEvent {
export const type = new NotificationType<RunspaceDetails, void>('powerShell/runspaceChanged');
}