forked from PowerShell/vscode-powershell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.ts
792 lines (662 loc) · 32.2 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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import fs = require("fs");
import net = require("net");
import path = require("path");
import * as semver from "semver";
import vscode = require("vscode");
import TelemetryReporter from "vscode-extension-telemetry";
import { Message } from "vscode-jsonrpc";
import { IFeature } from "./feature";
import { Logger } from "./logging";
import { PowerShellProcess } from "./process";
import Settings = require("./settings");
import utils = require("./utils");
import {
CloseAction, DocumentSelector, ErrorAction, LanguageClient, LanguageClientOptions,
Middleware, NotificationType, RequestType0,
ResolveCodeLensSignature, RevealOutputChannelOn, StreamInfo } from "vscode-languageclient";
import { GitHubReleaseInformation, InvokePowerShellUpdateCheck } from "./features/UpdatePowerShell";
import {
getPlatformDetails, IPlatformDetails, IPowerShellExeDetails,
OperatingSystem, PowerShellExeFinder } from "./platform";
export enum SessionStatus {
NeverStarted,
NotStarted,
Initializing,
Running,
Stopping,
Failed,
}
export class SessionManager implements Middleware {
public HostName: string;
public HostVersion: string;
public PowerShellExeDetails: IPowerShellExeDetails;
private ShowSessionMenuCommandName = "PowerShell.ShowSessionMenu";
private editorServicesArgs: string;
private sessionStatus: SessionStatus = SessionStatus.NeverStarted;
private suppressRestartPrompt: boolean;
private focusConsoleOnExecute: boolean;
private platformDetails: IPlatformDetails;
private extensionFeatures: IFeature[] = [];
private statusBarItem: vscode.StatusBarItem;
private languageServerProcess: PowerShellProcess;
private debugSessionProcess: PowerShellProcess;
private versionDetails: IPowerShellVersionDetails;
private registeredCommands: vscode.Disposable[] = [];
private languageServerClient: LanguageClient = undefined;
private sessionSettings: Settings.ISettings = undefined;
private sessionDetails: utils.IEditorServicesSessionDetails;
private bundledModulesPath: string;
// Initialized by the start() method, since this requires settings
private powershellExeFinder: PowerShellExeFinder;
// 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 log: Logger,
private documentSelector: DocumentSelector,
hostName: string,
version: string,
private telemetryReporter: TelemetryReporter) {
this.platformDetails = getPlatformDetails();
this.HostName = hostName;
this.HostVersion = version;
const osBitness = this.platformDetails.isOS64Bit ? "64-bit" : "32-bit";
const procBitness = this.platformDetails.isProcess64Bit ? "64-bit" : "32-bit";
this.log.write(
`Visual Studio Code v${vscode.version} ${procBitness}`,
`${this.HostName} Extension v${this.HostVersion}`,
`Operating System: ${OperatingSystem[this.platformDetails.operatingSystem]} ${osBitness}`);
// 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 dispose(): void {
// Stop the current session
this.stop();
// Dispose of all commands
this.registeredCommands.forEach((command) => { command.dispose(); });
}
public setExtensionFeatures(extensionFeatures: IFeature[]) {
this.extensionFeatures = extensionFeatures;
}
public start(exeNameOverride?: string) {
this.sessionSettings = Settings.load();
if (exeNameOverride) {
this.sessionSettings.powerShellDefaultVersion = exeNameOverride;
}
this.log.startNewLog(this.sessionSettings.developer.editorServicesLogLevel);
// Create the PowerShell executable finder now
this.powershellExeFinder = new PowerShellExeFinder(
this.platformDetails,
this.sessionSettings.powerShellAdditionalExePaths);
this.focusConsoleOnExecute = this.sessionSettings.integratedConsole.focusConsoleOnExecute;
this.createStatusBarItem();
this.promptPowerShellExeSettingsCleanup();
this.migrateWhitespaceAroundPipeSetting();
try {
let powerShellExeDetails;
if (this.sessionSettings.powerShellDefaultVersion) {
for (const details of this.powershellExeFinder.enumeratePowerShellInstallations()) {
// Need to compare names case-insensitively, from https://stackoverflow.com/a/2140723
const wantedName = this.sessionSettings.powerShellDefaultVersion;
if (wantedName.localeCompare(details.displayName, undefined, { sensitivity: "accent" }) === 0) {
powerShellExeDetails = details;
break;
}
}
}
this.PowerShellExeDetails = powerShellExeDetails ||
this.powershellExeFinder.getFirstAvailablePowerShellInstallation();
} catch (e) {
this.log.writeError(`Error occurred while searching for a PowerShell executable:\n${e}`);
}
this.suppressRestartPrompt = false;
if (!this.PowerShellExeDetails) {
const message = "Unable to find PowerShell."
+ " Do you have PowerShell installed?"
+ " You can also configure custom PowerShell installations"
+ " with the 'powershell.powerShellAdditionalExePaths' setting.";
this.log.writeAndShowErrorWithActions(message, [
{
prompt: "Get PowerShell",
action: async () => {
const getPSUri = vscode.Uri.parse("https://aka.ms/get-powershell-vscode");
vscode.env.openExternal(getPSUri);
},
},
]);
return;
}
this.bundledModulesPath = path.resolve(__dirname, this.sessionSettings.bundledModulesPath);
if (this.inDevelopmentMode) {
const devBundledModulesPath =
path.resolve(
__dirname,
this.sessionSettings.developer.bundledModulesPath);
// Make sure the module's bin path exists
if (fs.existsSync(path.join(devBundledModulesPath, "PowerShellEditorServices/bin"))) {
this.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`);
}
}
this.editorServicesArgs =
`-HostName 'Visual Studio Code Host' ` +
`-HostProfileId 'Microsoft.VSCode' ` +
`-HostVersion '${this.HostVersion}' ` +
`-AdditionalModules @('PowerShellEditorServices.VSCode') ` +
`-BundledModulesPath '${PowerShellProcess.escapeSingleQuotes(this.bundledModulesPath)}' ` +
`-EnableConsoleRepl `;
if (this.sessionSettings.integratedConsole.suppressStartupBanner) {
this.editorServicesArgs += "-StartupBanner '' ";
} else {
const startupBanner = `=====> ${this.HostName} Integrated Console v${this.HostVersion} <=====
`;
this.editorServicesArgs += `-StartupBanner '${startupBanner}' `;
}
if (this.sessionSettings.developer.editorServicesWaitForDebugger) {
this.editorServicesArgs += "-WaitForDebugger ";
}
if (this.sessionSettings.developer.editorServicesLogLevel) {
this.editorServicesArgs += `-LogLevel '${this.sessionSettings.developer.editorServicesLogLevel}' `;
}
this.startPowerShell();
}
public stop() {
// Shut down existing session if there is one
this.log.write("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.languageServerProcess = undefined;
}
this.sessionStatus = SessionStatus.Stopping;
// Close the language server client
if (this.languageServerClient !== undefined) {
this.languageServerClient.stop();
this.languageServerClient = undefined;
}
// Kill the PowerShell proceses we spawned
if (this.debugSessionProcess) {
this.debugSessionProcess.dispose();
}
if (this.languageServerProcess) {
this.languageServerProcess.dispose();
}
this.sessionStatus = SessionStatus.NotStarted;
}
public restartSession(exeNameOverride?: string) {
this.stop();
this.start(exeNameOverride);
}
public getSessionDetails(): utils.IEditorServicesSessionDetails {
return this.sessionDetails;
}
public getSessionStatus(): SessionStatus {
return this.sessionStatus;
}
public getPowerShellVersionDetails(): IPowerShellVersionDetails {
return this.versionDetails;
}
public createDebugSessionProcess(
sessionPath: string,
sessionSettings: Settings.ISettings): PowerShellProcess {
this.debugSessionProcess =
new PowerShellProcess(
this.PowerShellExeDetails.exePath,
this.bundledModulesPath,
"[TEMP] PowerShell Integrated Console",
this.log,
this.editorServicesArgs + "-DebugServiceOnly ",
sessionPath,
sessionSettings);
return this.debugSessionProcess;
}
// ----- LanguageClient middleware methods -----
public resolveCodeLens(
codeLens: vscode.CodeLens,
token: vscode.CancellationToken,
next: ResolveCodeLensSignature): vscode.ProviderResult<vscode.CodeLens> {
const resolvedCodeLens = next(codeLens, token);
const resolveFunc =
(codeLensToFix: vscode.CodeLens): vscode.CodeLens => {
if (codeLensToFix.command?.command === "editor.action.showReferences") {
const oldArgs = codeLensToFix.command.arguments;
// Our JSON objects don't get handled correctly by
// VS Code's built in editor.action.showReferences
// command so we need to convert them into the
// appropriate types to send them as command
// arguments.
codeLensToFix.command.arguments = [
vscode.Uri.parse(oldArgs[0]),
new vscode.Position(oldArgs[1].line, oldArgs[1].character),
oldArgs[2].map((position) => {
return new vscode.Location(
vscode.Uri.parse(position.uri),
new vscode.Range(
position.range.start.line,
position.range.start.character,
position.range.end.line,
position.range.end.character));
}),
];
}
return codeLensToFix;
};
if ((resolvedCodeLens as Thenable<vscode.CodeLens>).then) {
return (resolvedCodeLens as Thenable<vscode.CodeLens>).then(resolveFunc);
} else if (resolvedCodeLens as vscode.CodeLens) {
return resolveFunc(resolvedCodeLens as vscode.CodeLens);
}
return resolvedCodeLens;
}
// During preview, populate a new setting value but not remove the old value.
// TODO: When the next stable extension releases, then the old value can be safely removed. Tracked in this issue: https://github.com/PowerShell/vscode-powershell/issues/2693
private async migrateWhitespaceAroundPipeSetting() {
const configuration = vscode.workspace.getConfiguration(utils.PowerShellLanguageId);
const deprecatedSetting = 'codeFormatting.whitespaceAroundPipe'
const newSetting = 'codeFormatting.addWhitespaceAroundPipe'
const configurationTargetOfNewSetting = await Settings.getEffectiveConfigurationTarget(newSetting);
if (configuration.has(deprecatedSetting) && configurationTargetOfNewSetting === null) {
const configurationTarget = await Settings.getEffectiveConfigurationTarget(deprecatedSetting);
const value = configuration.get(deprecatedSetting, configurationTarget)
await Settings.change(newSetting, value, configurationTarget);
}
}
private async promptPowerShellExeSettingsCleanup() {
if (this.sessionSettings.powerShellExePath) {
let warningMessage = "The 'powerShell.powerShellExePath' setting is no longer used. ";
warningMessage += this.sessionSettings.powerShellDefaultVersion
? "We can automatically remove it for you."
: "We can remove it from your settings and prompt you for which PowerShell you want to use.";
const choice = await vscode.window.showWarningMessage(warningMessage, "Let's do it!");
if (choice === undefined) {
// They hit the 'x' to close the dialog.
return;
}
this.suppressRestartPrompt = true;
try {
await Settings.change("powerShellExePath", undefined, true);
} finally {
this.suppressRestartPrompt = false;
}
// Show the session menu at the end if they don't have a PowerShellDefaultVersion.
if (!this.sessionSettings.powerShellDefaultVersion) {
await vscode.commands.executeCommand(this.ShowSessionMenuCommandName);
}
}
}
private onConfigurationUpdated() {
const settings = Settings.load();
this.focusConsoleOnExecute = settings.integratedConsole.focusConsoleOnExecute;
// Detect any setting changes that would affect the session
if (!this.suppressRestartPrompt &&
(settings.useX86Host !==
this.sessionSettings.useX86Host ||
settings.powerShellDefaultVersion.toLowerCase() !==
this.sessionSettings.powerShellDefaultVersion.toLowerCase() ||
settings.developer.editorServicesLogLevel.toLowerCase() !==
this.sessionSettings.developer.editorServicesLogLevel.toLowerCase() ||
settings.developer.bundledModulesPath.toLowerCase() !==
this.sessionSettings.developer.bundledModulesPath.toLowerCase() ||
settings.integratedConsole.useLegacyReadLine !==
this.sessionSettings.integratedConsole.useLegacyReadLine)) {
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();
}
});
}
}
private setStatusBarVersionString(runspaceDetails: IRunspaceDetails) {
const psVersion = runspaceDetails.powerShellVersion;
let versionString =
this.versionDetails.architecture === "x86"
? `${psVersion.displayVersion} (${psVersion.architecture})`
: psVersion.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() {
this.setSessionStatus(
"Starting PowerShell...",
SessionStatus.Initializing);
const sessionFilePath =
utils.getSessionFilePath(
Math.floor(100000 + Math.random() * 900000));
this.languageServerProcess =
new PowerShellProcess(
this.PowerShellExeDetails.exePath,
this.bundledModulesPath,
"PowerShell Integrated Console",
this.log,
this.editorServicesArgs,
sessionFilePath,
this.sessionSettings);
this.languageServerProcess.onExited(
() => {
if (this.sessionStatus === SessionStatus.Running) {
this.setSessionStatus("Session exited", SessionStatus.Failed);
this.promptForRestart();
}
});
this.languageServerProcess
.start("EditorServices")
.then(
(sessionDetails) => {
this.sessionDetails = sessionDetails;
if (sessionDetails.status === "started") {
this.log.write("Language server started.");
// 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 5.1 and 6.1" +
` 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
}
},
(error) => {
this.log.write("Language server startup failed.");
this.setSessionFailure("The language service could not be started: ", error);
},
)
.catch((error) => {
this.log.write("Language server startup failed.");
this.setSessionFailure("The language server could not be started: ", error);
});
}
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.IEditorServicesSessionDetails) {
// Log the session details object
this.log.write(JSON.stringify(sessionDetails));
try {
this.log.write(`Connecting to language service on pipe ${sessionDetails.languageServicePipeName}...`);
const connectFunc = () => {
return new Promise<StreamInfo>(
(resolve, reject) => {
const socket = net.connect(sessionDetails.languageServicePipeName);
socket.on(
"connect",
() => {
this.log.write("Language service connected.");
resolve({writer: socket, reader: socket});
});
});
};
const clientOptions: LanguageClientOptions = {
documentSelector: this.documentSelector,
synchronize: {
// backend uses "files" and "search" to ignore references.
configurationSection: [ utils.PowerShellLanguageId, "files", "search" ],
// 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;
},
},
revealOutputChannelOn: RevealOutputChannelOn.Never,
middleware: this,
};
this.languageServerClient =
new LanguageClient(
"PowerShell Editor Services",
connectFunc,
clientOptions);
this.languageServerClient.registerProposedFeatures();
this.languageServerClient.onReady().then(
() => {
this.languageServerClient
.sendRequest(PowerShellVersionRequestType)
.then(
async (versionDetails) => {
this.versionDetails = versionDetails;
if (!this.inDevelopmentMode) {
this.telemetryReporter.sendTelemetryEvent("powershellVersionCheck",
{ powershellVersion: versionDetails.version });
}
this.setSessionStatus(
this.versionDetails.architecture === "x86"
? `${this.versionDetails.displayVersion} (${this.versionDetails.architecture})`
: this.versionDetails.displayVersion,
SessionStatus.Running);
// If the user opted to not check for updates, then don't.
if (!this.sessionSettings.promptToUpdatePowerShell) { return; }
try {
const localVersion = semver.parse(this.versionDetails.version);
if (semver.lt(localVersion, "6.0.0")) {
// Skip prompting when using Windows PowerShell for now.
return;
}
// Fetch the latest PowerShell releases from GitHub.
const isPreRelease = !!semver.prerelease(localVersion);
const release: GitHubReleaseInformation =
await GitHubReleaseInformation.FetchLatestRelease(isPreRelease);
await InvokePowerShellUpdateCheck(
this,
this.languageServerClient,
localVersion,
this.versionDetails.architecture,
release);
} catch (e) {
// best effort. This probably failed to fetch the data from GitHub.
this.log.writeWarning(e.message);
}
});
// 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(
RunspaceChangedEventType,
(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 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.tooltip = "Show PowerShell Session Menu";
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
let statusIconText = "$(terminal) ";
let 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 async changePowerShellDefaultVersion(exePath: IPowerShellExeDetails) {
this.suppressRestartPrompt = true;
await Settings.change("powerShellDefaultVersion", exePath.displayName, true);
// We pass in the display name so that we force the extension to use that version
// rather than pull from the settings. The issue we prevent here is when a
// workspace setting is defined which gets priority over user settings which
// is what the change above sets.
this.restartSession(exePath.displayName);
}
private showSessionConsole(isExecute?: boolean) {
if (this.languageServerProcess) {
this.languageServerProcess.showConsole(isExecute && !this.focusConsoleOnExecute);
}
}
private showSessionMenu() {
const availablePowerShellExes = this.powershellExeFinder.getAllAvailablePowerShellInstallations();
let sessionText: string;
switch (this.sessionStatus) {
case SessionStatus.Running:
case SessionStatus.Initializing:
case SessionStatus.NotStarted:
case SessionStatus.NeverStarted:
case SessionStatus.Stopping:
const currentPowerShellExe =
availablePowerShellExes
.find((item) => item.displayName.toLowerCase() === this.PowerShellExeDetails.displayName);
const powerShellSessionName =
currentPowerShellExe ?
currentPowerShellExe.displayName :
`PowerShell ${this.versionDetails.displayVersion} ` +
`(${this.versionDetails.architecture}) ${this.versionDetails.edition} Edition ` +
`[${this.versionDetails.version}]`;
sessionText = `Current session: ${powerShellSessionName}`;
break;
case SessionStatus.Failed:
sessionText = "Session initialization failed, click here to show PowerShell extension logs";
break;
default:
throw new TypeError("Not a valid value for the enum 'SessionStatus'");
}
const powerShellItems =
availablePowerShellExes
.filter((item) => item.displayName !== this.PowerShellExeDetails.displayName)
.map((item) => {
return new SessionMenuItem(
`Switch to: ${item.displayName}`,
() => { this.changePowerShellDefaultVersion(item); });
});
const menuItems: SessionMenuItem[] = [
new SessionMenuItem(
sessionText,
() => { vscode.commands.executeCommand("PowerShell.ShowLogs"); }),
// Add all of the different PowerShell options
...powerShellItems,
new SessionMenuItem(
"Restart Current Session",
() => {
// We pass in the display name so we guarentee that the session
// will be the same PowerShell.
this.restartSession(this.PowerShellExeDetails.displayName);
}),
new SessionMenuItem(
"Open Session Logs Folder",
() => { vscode.commands.executeCommand("PowerShell.OpenLogFolder"); }),
new SessionMenuItem(
"Modify 'powerShell.powerShellAdditionalExePaths' in Settings",
() => { vscode.commands.executeCommand("workbench.action.openSettingsJson"); }),
];
vscode
.window
.showQuickPick<SessionMenuItem>(menuItems)
.then((selectedItem) => { selectedItem.callback(); });
}
}
class SessionMenuItem implements vscode.QuickPickItem {
public description: string;
constructor(
public readonly label: string,
// tslint:disable-next-line:no-empty
public readonly callback: () => void = () => {}) {
}
}
export const PowerShellVersionRequestType =
new RequestType0<IPowerShellVersionDetails, void, void>(
"powerShell/getVersion");
export const RunspaceChangedEventType =
new NotificationType<IRunspaceDetails, void>(
"powerShell/runspaceChanged");
export enum RunspaceType {
Local,
Process,
Remote,
}
export interface IPowerShellVersionDetails {
version: string;
displayVersion: string;
edition: string;
architecture: string;
}
export interface IRunspaceDetails {
powerShellVersion: IPowerShellVersionDetails;
runspaceType: RunspaceType;
connectionString: string;
}