Skip to content

Commit 81a3801

Browse files
prompt to update PackageManagement if it is older than 1.4.6
1 parent 6e3fa17 commit 81a3801

File tree

6 files changed

+122
-14
lines changed

6 files changed

+122
-14
lines changed

src/PowerShellEditorServices/Services/PowerShellContext/Handlers/GetCommandHandler.cs

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,18 @@
33
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
44
//
55

6+
using System;
67
using System.Collections.Generic;
78
using System.Management.Automation;
9+
using System.Text;
810
using System.Threading;
911
using System.Threading.Tasks;
1012
using Microsoft.Extensions.Logging;
1113
using Microsoft.PowerShell.EditorServices.Services;
1214
using MediatR;
1315
using OmniSharp.Extensions.JsonRpc;
16+
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
17+
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
1418

1519
namespace Microsoft.PowerShell.EditorServices.Handlers
1620
{
@@ -48,29 +52,38 @@ public async Task<List<PSCommandMessage>> Handle(GetCommandParams request, Cance
4852
PSCommand psCommand = new PSCommand();
4953

5054
// Executes the following:
51-
// Get-Command -CommandType Function,Cmdlet,ExternalScript | Select-Object -Property Name,ModuleName | Sort-Object -Property Name
55+
// Get-Command -CommandType Function,Cmdlet,ExternalScript | Sort-Object -Property Name
5256
psCommand
5357
.AddCommand("Microsoft.PowerShell.Core\\Get-Command")
5458
.AddParameter("CommandType", new[] { "Function", "Cmdlet", "ExternalScript" })
55-
.AddCommand("Microsoft.PowerShell.Utility\\Select-Object")
56-
.AddParameter("Property", new[] { "Name", "ModuleName" })
5759
.AddCommand("Microsoft.PowerShell.Utility\\Sort-Object")
5860
.AddParameter("Property", "Name");
5961

60-
IEnumerable<PSObject> result = await _powerShellContextService.ExecuteCommandAsync<PSObject>(psCommand).ConfigureAwait(false);
62+
IEnumerable<CommandInfo> result = await _powerShellContextService.ExecuteCommandAsync<CommandInfo>(psCommand).ConfigureAwait(false);
6163

6264
var commandList = new List<PSCommandMessage>();
6365
if (result != null)
6466
{
65-
foreach (dynamic command in result)
67+
foreach (CommandInfo command in result)
6668
{
69+
// Get the default ParameterSet
70+
string defaultParameterSet = null;
71+
foreach (CommandParameterSetInfo parameterSetInfo in command.ParameterSets)
72+
{
73+
if (parameterSetInfo.IsDefault)
74+
{
75+
defaultParameterSet = parameterSetInfo.Name;
76+
break;
77+
}
78+
}
79+
6780
commandList.Add(new PSCommandMessage
6881
{
6982
Name = command.Name,
7083
ModuleName = command.ModuleName,
7184
Parameters = command.Parameters,
7285
ParameterSets = command.ParameterSets,
73-
DefaultParameterSet = command.DefaultParameterSet
86+
DefaultParameterSet = defaultParameterSet
7487
});
7588
}
7689
}

src/PowerShellEditorServices/Services/PowerShellContext/Handlers/GetVersionHandler.cs

Lines changed: 90 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,41 @@
44
//
55

66
using System;
7+
using System.Management.Automation;
8+
using System.Text;
79
using System.Threading;
810
using System.Threading.Tasks;
911
using Microsoft.Extensions.Logging;
12+
using Microsoft.PowerShell.EditorServices.Services;
13+
using Microsoft.PowerShell.EditorServices.Services.PowerShellContext;
1014
using Microsoft.PowerShell.EditorServices.Utility;
15+
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
16+
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
1117

1218
namespace Microsoft.PowerShell.EditorServices.Handlers
1319
{
1420
internal class GetVersionHandler : IGetVersionHandler
1521
{
22+
private static readonly Version s_desiredPackageManagementVersion = new Version(1, 4, 6);
23+
1624
private readonly ILogger<GetVersionHandler> _logger;
25+
private readonly PowerShellContextService _powerShellContextService;
26+
private readonly ILanguageServer _languageServer;
27+
private readonly ConfigurationService _configurationService;
1728

18-
public GetVersionHandler(ILoggerFactory factory)
29+
public GetVersionHandler(
30+
ILoggerFactory factory,
31+
PowerShellContextService powerShellContextService,
32+
ILanguageServer languageServer,
33+
ConfigurationService configurationService)
1934
{
2035
_logger = factory.CreateLogger<GetVersionHandler>();
36+
_powerShellContextService = powerShellContextService;
37+
_languageServer = languageServer;
38+
_configurationService = configurationService;
2139
}
2240

23-
public Task<PowerShellVersion> Handle(GetVersionParams request, CancellationToken cancellationToken)
41+
public async Task<PowerShellVersion> Handle(GetVersionParams request, CancellationToken cancellationToken)
2442
{
2543
var architecture = PowerShellProcessArchitecture.Unknown;
2644
// This should be changed to using a .NET call sometime in the future... but it's just for logging purposes.
@@ -37,13 +55,18 @@ public Task<PowerShellVersion> Handle(GetVersionParams request, CancellationToke
3755
}
3856
}
3957

40-
return Task.FromResult(new PowerShellVersion
58+
if (VersionUtils.IsPS5 && _configurationService.CurrentSettings.PromptToUpdatePackageManagement)
59+
{
60+
await CheckPackageManagement().ConfigureAwait(false);
61+
}
62+
63+
return new PowerShellVersion
4164
{
4265
Version = VersionUtils.PSVersionString,
4366
Edition = VersionUtils.PSEdition,
4467
DisplayVersion = VersionUtils.PSVersion.ToString(2),
4568
Architecture = architecture.ToString()
46-
});
69+
};
4770
}
4871

4972
private enum PowerShellProcessArchitecture
@@ -52,5 +75,68 @@ private enum PowerShellProcessArchitecture
5275
X86,
5376
X64
5477
}
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. Attempting to update.");
91+
92+
var takeActionText = "Yes";
93+
MessageActionItem messageAction = await _languageServer.Window.ShowMessage(new ShowMessageRequestParams
94+
{
95+
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)?",
96+
Type = MessageType.Warning,
97+
Actions = new []
98+
{
99+
new MessageActionItem
100+
{
101+
Title = takeActionText
102+
},
103+
new MessageActionItem
104+
{
105+
Title = "Not now"
106+
}
107+
}
108+
});
109+
110+
// If the user chose "Not now" ignore it for the rest of the session.
111+
if (messageAction?.Title == takeActionText)
112+
{
113+
StringBuilder errors = new StringBuilder();
114+
await _powerShellContextService.ExecuteScriptStringAsync(
115+
"powershell.exe -NoLogo -NoProfile -Command 'Install-Module -Name PackageManagement -Force -MinimumVersion 1.4.6 -Scope CurrentUser -AllowClobber'",
116+
errors,
117+
writeInputToHost: true,
118+
writeOutputToHost: true,
119+
addToHistory: true).ConfigureAwait(false);
120+
121+
// There were errors installing PackageManagement.
122+
if (errors.Length == 0)
123+
{
124+
_languageServer.Window.ShowMessage(new ShowMessageParams
125+
{
126+
Type = MessageType.Info,
127+
Message = "PackageManagement updated, If you already had PackageManagement loaded in your session, please restart the PowerShell extension."
128+
});
129+
}
130+
else
131+
{
132+
_languageServer.Window.ShowMessage(new ShowMessageParams
133+
{
134+
Type = MessageType.Error,
135+
Message = "PackageManagement update failed. Please run the following command in a Windows PowerShell prompt and restart the PowerShell extension: `Install-Module PackageManagement -Force -AllowClobber -MinimumVersion 1.4.6`"
136+
});
137+
}
138+
}
139+
}
140+
}
55141
}
56142
}

src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,7 @@ public async Task<IEnumerable<TResult>> ExecuteCommandAsync<TResult>(
597597
// cancelled prompt when it's called again.
598598
if (executionOptions.AddToHistory)
599599
{
600-
this.PromptContext.AddToHistory(psCommand.Commands[0].CommandText);
600+
this.PromptContext.AddToHistory(executionOptions.InputString ?? psCommand.Commands[0].CommandText);
601601
}
602602

603603
bool hadErrors = false;
@@ -686,7 +686,7 @@ public async Task<IEnumerable<TResult>> ExecuteCommandAsync<TResult>(
686686
if (executionOptions.WriteInputToHost)
687687
{
688688
this.WriteOutput(
689-
psCommand.Commands[0].CommandText,
689+
executionOptions.InputString ?? psCommand.Commands[0].CommandText,
690690
includeNewLine: true);
691691
}
692692

src/PowerShellEditorServices/Services/PowerShellContext/Session/ExecutionOptions.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ internal class ExecutionOptions
4646
/// </summary>
4747
public bool WriteInputToHost { get; set; }
4848

49+
/// <summary>
50+
/// If this is set, we will use this string for history and writing to the host
51+
/// instead of grabbing the command from the PSCommand.
52+
/// </summary>
53+
public string InputString { get; set; }
54+
4955
/// <summary>
5056
/// Gets or sets a value indicating whether the command to
5157
/// be executed is a console input prompt, such as the

src/PowerShellEditorServices/Services/Workspace/LanguageServerSettings.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ internal class LanguageServerSettings
2020
private readonly object updateLock = new object();
2121
public bool EnableProfileLoading { get; set; }
2222

23+
public bool PromptToUpdatePackageManagement { get; set; }
24+
2325
public ScriptAnalysisSettings ScriptAnalysis { get; set; }
2426

2527
public CodeFormattingSettings CodeFormatting { get; set; }
@@ -46,6 +48,7 @@ public void Update(
4648
lock (updateLock)
4749
{
4850
this.EnableProfileLoading = settings.EnableProfileLoading;
51+
this.PromptToUpdatePackageManagement = settings.PromptToUpdatePackageManagement;
4952
this.ScriptAnalysis.Update(
5053
settings.ScriptAnalysis,
5154
workspaceRootPath,

test/PowerShellEditorServices.Test.E2E/LanguageServerProtocolMessageTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1004,8 +1004,8 @@ await LanguageClient.SendRequest<EvaluateResponseBody>(
10041004
[Fact]
10051005
public async Task CanSendGetCommandRequest()
10061006
{
1007-
List<PSCommandMessage> pSCommandMessages =
1008-
await LanguageClient.SendRequest<List<PSCommandMessage>>("powerShell/getCommand", new GetCommandParams());
1007+
List<object> pSCommandMessages =
1008+
await LanguageClient.SendRequest<List<object>>("powerShell/getCommand", new GetCommandParams());
10091009

10101010
Assert.NotEmpty(pSCommandMessages);
10111011
// There should be at least 20 commands or so.

0 commit comments

Comments
 (0)