Skip to content

Commit f0f367f

Browse files
Fix issue #62 to show the correct status of the PowerShell console (#67)
* Add GetVersionHandler to language server * update .vscodeignore Co-authored-by: Yunchi Wang <54880216+wyunchi-ms@users.noreply.github.com>
1 parent ad3f142 commit f0f367f

File tree

4 files changed

+160
-11
lines changed

4 files changed

+160
-11
lines changed

vscode-extension/.vscodeignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ vsc-extension-quickstart.md
1010
**/*.ts
1111
server/**
1212
!server/module/**
13+
resources/**

vscode-extension/server/src/PowerShellEditorServices/Server/PsesLanguageServer.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ public async Task StartAsync()
7070
.AddLanguageProtocolLogging(_minimumLogLevel)
7171
.SetMinimumLevel(_minimumLogLevel))
7272
.WithHandler<PsesTextDocumentHandler>()
73+
.WithHandler<GetVersionHandler>()
7374
.WithHandler<PsesCodeActionHandler>()
7475
.OnInitialize(
7576
async (languageServer, request, cancellationToken) =>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
//
2+
// Copyright (c) Microsoft. All rights reserved.
3+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
4+
//
5+
6+
using System;
7+
using System.Management.Automation;
8+
using System.Text;
9+
using System.Threading;
10+
using System.Threading.Tasks;
11+
using Microsoft.Extensions.Logging;
12+
using Microsoft.PowerShell.EditorServices.Services;
13+
using Microsoft.PowerShell.EditorServices.Utility;
14+
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
15+
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
16+
using OmniSharp.Extensions.LanguageServer.Protocol.Window;
17+
18+
namespace Microsoft.PowerShell.EditorServices.Handlers
19+
{
20+
internal class GetVersionHandler : IGetVersionHandler
21+
{
22+
private static readonly Version s_desiredPackageManagementVersion = new Version(1, 4, 6);
23+
24+
private readonly ILogger<GetVersionHandler> _logger;
25+
private readonly PowerShellContextService _powerShellContextService;
26+
private readonly ILanguageServer _languageServer;
27+
private readonly ConfigurationService _configurationService;
28+
29+
public GetVersionHandler(
30+
ILoggerFactory factory,
31+
PowerShellContextService powerShellContextService,
32+
ILanguageServer languageServer,
33+
ConfigurationService configurationService)
34+
{
35+
_logger = factory.CreateLogger<GetVersionHandler>();
36+
_powerShellContextService = powerShellContextService;
37+
_languageServer = languageServer;
38+
_configurationService = configurationService;
39+
}
40+
41+
public async Task<PowerShellVersion> Handle(GetVersionParams request, CancellationToken cancellationToken)
42+
{
43+
var architecture = PowerShellProcessArchitecture.Unknown;
44+
// This should be changed to using a .NET call sometime in the future... but it's just for logging purposes.
45+
string arch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
46+
if (arch != null)
47+
{
48+
if (string.Equals(arch, "AMD64", StringComparison.CurrentCultureIgnoreCase))
49+
{
50+
architecture = PowerShellProcessArchitecture.X64;
51+
}
52+
else if (string.Equals(arch, "x86", StringComparison.CurrentCultureIgnoreCase))
53+
{
54+
architecture = PowerShellProcessArchitecture.X86;
55+
}
56+
}
57+
58+
if (VersionUtils.IsPS5 && _configurationService.CurrentSettings.PromptToUpdatePackageManagement)
59+
{
60+
await CheckPackageManagement().ConfigureAwait(false);
61+
}
62+
63+
return new PowerShellVersion
64+
{
65+
Version = VersionUtils.PSVersionString,
66+
Edition = VersionUtils.PSEdition,
67+
DisplayVersion = VersionUtils.PSVersion.ToString(2),
68+
Architecture = architecture.ToString()
69+
};
70+
}
71+
72+
private enum PowerShellProcessArchitecture
73+
{
74+
Unknown,
75+
X86,
76+
X64
77+
}
78+
79+
private async Task CheckPackageManagement()
80+
{
81+
PSCommand getModule = new PSCommand().AddCommand("Get-Module").AddParameter("ListAvailable").AddParameter("Name", "PackageManagement");
82+
foreach (PSModuleInfo module in await _powerShellContextService.ExecuteCommandAsync<PSModuleInfo>(getModule))
83+
{
84+
// The user has a good enough version of PackageManagement
85+
if (module.Version >= s_desiredPackageManagementVersion)
86+
{
87+
break;
88+
}
89+
90+
_logger.LogDebug("Old version of PackageManagement detected.");
91+
92+
if (_powerShellContextService.CurrentRunspace.Runspace.SessionStateProxy.LanguageMode != PSLanguageMode.FullLanguage)
93+
{
94+
_languageServer.Window.ShowWarning("You have an older version of PackageManagement known to cause issues with the PowerShell extension. Please run the following command in a new Windows PowerShell session and then restart the PowerShell extension: `Install-Module PackageManagement -Force -AllowClobber -MinimumVersion 1.4.6`");
95+
return;
96+
}
97+
98+
var takeActionText = "Yes";
99+
MessageActionItem messageAction = await _languageServer.Window.ShowMessageRequest(new ShowMessageRequestParams
100+
{
101+
Message = "You have an older version of PackageManagement known to cause issues with the PowerShell extension. Would you like to update PackageManagement (You will need to restart the PowerShell extension after)?",
102+
Type = MessageType.Warning,
103+
Actions = new[]
104+
{
105+
new MessageActionItem
106+
{
107+
Title = takeActionText
108+
},
109+
new MessageActionItem
110+
{
111+
Title = "Not now"
112+
}
113+
}
114+
});
115+
116+
// If the user chose "Not now" ignore it for the rest of the session.
117+
if (messageAction?.Title == takeActionText)
118+
{
119+
StringBuilder errors = new StringBuilder();
120+
await _powerShellContextService.ExecuteScriptStringAsync(
121+
"powershell.exe -NoLogo -NoProfile -Command '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Install-Module -Name PackageManagement -Force -MinimumVersion 1.4.6 -Scope CurrentUser -AllowClobber -Repository PSGallery'",
122+
errors,
123+
writeInputToHost: true,
124+
writeOutputToHost: true,
125+
addToHistory: true).ConfigureAwait(false);
126+
127+
if (errors.Length == 0)
128+
{
129+
_logger.LogDebug("PackageManagement is updated.");
130+
_languageServer.Window.ShowMessage(new ShowMessageParams
131+
{
132+
Type = MessageType.Info,
133+
Message = "PackageManagement updated, If you already had PackageManagement loaded in your session, please restart the PowerShell extension."
134+
});
135+
}
136+
else
137+
{
138+
// There were errors installing PackageManagement.
139+
_logger.LogError($"PackageManagement installation had errors: {errors.ToString()}");
140+
_languageServer.Window.ShowMessage(new ShowMessageParams
141+
{
142+
Type = MessageType.Error,
143+
Message = "PackageManagement update failed. This might be due to PowerShell Gallery using TLS 1.2. More info can be found at https://aka.ms/psgallerytls"
144+
});
145+
}
146+
}
147+
}
148+
}
149+
}
150+
}

vscode-extension/src/session.ts

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -362,9 +362,9 @@ export class SessionManager implements Middleware {
362362
}
363363

364364
// Show the session menu at the end if they don't have a PowerShellDefaultVersion.
365-
// if (!this.sessionSettings.powerShellDefaultVersion) {
366-
// await vscode.commands.executeCommand(this.ShowSessionMenuCommandName);
367-
// }
365+
if (!this.sessionSettings.powerShellDefaultVersion) {
366+
await vscode.commands.executeCommand(this.ShowSessionMenuCommandName);
367+
}
368368
}
369369
}
370370

@@ -418,7 +418,7 @@ export class SessionManager implements Middleware {
418418
private registerCommands(): void {
419419
this.registeredCommands = [
420420
vscode.commands.registerCommand("AzurePowerShell.RestartSession", () => { this.restartSession(); }),
421-
// vscode.commands.registerCommand(this.ShowSessionMenuCommandName, () => { this.showSessionMenu(); }),
421+
vscode.commands.registerCommand(this.ShowSessionMenuCommandName, () => { this.showSessionMenu(); }),
422422
vscode.workspace.onDidChangeConfiguration(() => this.onConfigurationUpdated()),
423423
vscode.commands.registerCommand(
424424
"AzurePowerShell.ShowSessionConsole", (isExecute?: boolean) => { this.showSessionConsole(isExecute); }),
@@ -427,13 +427,10 @@ export class SessionManager implements Middleware {
427427

428428
private startPowerShell() {
429429

430-
// this.setSessionStatus(
431-
// "Starting PowerShell...",
432-
// SessionStatus.Initializing);
433-
// TODO Fix the issue: https://github.com/Azure/azure-powershell-migration/issues/62
434430
this.setSessionStatus(
435-
"Azure Powershell",
436-
SessionStatus.Running);
431+
"Starting PowerShell...",
432+
SessionStatus.Initializing);
433+
437434
const sessionFilePath =
438435
utils.getSessionFilePath(
439436
Math.floor(100000 + Math.random() * 900000));
@@ -632,7 +629,7 @@ export class SessionManager implements Middleware {
632629
vscode.StatusBarAlignment.Right,
633630
1);
634631

635-
// this.statusBarItem.command = this.ShowSessionMenuCommandName;
632+
this.statusBarItem.command = this.ShowSessionMenuCommandName;
636633
this.statusBarItem.tooltip = "Show Azure PowerShell Tools Session Menu";
637634
this.statusBarItem.show();
638635
vscode.window.onDidChangeActiveTextEditor((textEditor) => {

0 commit comments

Comments
 (0)