Skip to content

Commit

Permalink
prompt to update PackageManagement if it is older than 1.4.6
Browse files Browse the repository at this point in the history
  • Loading branch information
TylerLeonhardt committed Apr 21, 2020
1 parent 6e3fa17 commit 81a3801
Show file tree
Hide file tree
Showing 6 changed files with 122 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.PowerShell.EditorServices.Services;
using MediatR;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;

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

// Executes the following:
// Get-Command -CommandType Function,Cmdlet,ExternalScript | Select-Object -Property Name,ModuleName | Sort-Object -Property Name
// Get-Command -CommandType Function,Cmdlet,ExternalScript | Sort-Object -Property Name
psCommand
.AddCommand("Microsoft.PowerShell.Core\\Get-Command")
.AddParameter("CommandType", new[] { "Function", "Cmdlet", "ExternalScript" })
.AddCommand("Microsoft.PowerShell.Utility\\Select-Object")
.AddParameter("Property", new[] { "Name", "ModuleName" })
.AddCommand("Microsoft.PowerShell.Utility\\Sort-Object")
.AddParameter("Property", "Name");

IEnumerable<PSObject> result = await _powerShellContextService.ExecuteCommandAsync<PSObject>(psCommand).ConfigureAwait(false);
IEnumerable<CommandInfo> result = await _powerShellContextService.ExecuteCommandAsync<CommandInfo>(psCommand).ConfigureAwait(false);

var commandList = new List<PSCommandMessage>();
if (result != null)
{
foreach (dynamic command in result)
foreach (CommandInfo command in result)
{
// Get the default ParameterSet
string defaultParameterSet = null;
foreach (CommandParameterSetInfo parameterSetInfo in command.ParameterSets)
{
if (parameterSetInfo.IsDefault)
{
defaultParameterSet = parameterSetInfo.Name;
break;
}
}

commandList.Add(new PSCommandMessage
{
Name = command.Name,
ModuleName = command.ModuleName,
Parameters = command.Parameters,
ParameterSets = command.ParameterSets,
DefaultParameterSet = command.DefaultParameterSet
DefaultParameterSet = defaultParameterSet
});
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,41 @@
//

using System;
using System.Management.Automation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.PowerShell.EditorServices.Services;
using Microsoft.PowerShell.EditorServices.Services.PowerShellContext;
using Microsoft.PowerShell.EditorServices.Utility;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.Extensions.LanguageServer.Protocol.Server;

namespace Microsoft.PowerShell.EditorServices.Handlers
{
internal class GetVersionHandler : IGetVersionHandler
{
private static readonly Version s_desiredPackageManagementVersion = new Version(1, 4, 6);

private readonly ILogger<GetVersionHandler> _logger;
private readonly PowerShellContextService _powerShellContextService;
private readonly ILanguageServer _languageServer;
private readonly ConfigurationService _configurationService;

public GetVersionHandler(ILoggerFactory factory)
public GetVersionHandler(
ILoggerFactory factory,
PowerShellContextService powerShellContextService,
ILanguageServer languageServer,
ConfigurationService configurationService)
{
_logger = factory.CreateLogger<GetVersionHandler>();
_powerShellContextService = powerShellContextService;
_languageServer = languageServer;
_configurationService = configurationService;
}

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

return Task.FromResult(new PowerShellVersion
if (VersionUtils.IsPS5 && _configurationService.CurrentSettings.PromptToUpdatePackageManagement)
{
await CheckPackageManagement().ConfigureAwait(false);
}

return new PowerShellVersion
{
Version = VersionUtils.PSVersionString,
Edition = VersionUtils.PSEdition,
DisplayVersion = VersionUtils.PSVersion.ToString(2),
Architecture = architecture.ToString()
});
};
}

private enum PowerShellProcessArchitecture
Expand All @@ -52,5 +75,68 @@ private enum PowerShellProcessArchitecture
X86,
X64
}

private async Task CheckPackageManagement()
{
PSCommand getModule = new PSCommand().AddCommand("Get-Module").AddParameter("ListAvailable").AddParameter("Name", "PackageManagement");
foreach (PSModuleInfo module in await _powerShellContextService.ExecuteCommandAsync<PSModuleInfo>(getModule))
{
// The user has a good enough version of PackageManagement
if(module.Version >= s_desiredPackageManagementVersion)
{
break;
}

_logger.LogDebug("Old version of PackageManagement detected. Attempting to update.");

var takeActionText = "Yes";
MessageActionItem messageAction = await _languageServer.Window.ShowMessage(new ShowMessageRequestParams
{
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)?",
Type = MessageType.Warning,
Actions = new []
{
new MessageActionItem
{
Title = takeActionText
},
new MessageActionItem
{
Title = "Not now"
}
}
});

// If the user chose "Not now" ignore it for the rest of the session.
if (messageAction?.Title == takeActionText)
{
StringBuilder errors = new StringBuilder();
await _powerShellContextService.ExecuteScriptStringAsync(
"powershell.exe -NoLogo -NoProfile -Command 'Install-Module -Name PackageManagement -Force -MinimumVersion 1.4.6 -Scope CurrentUser -AllowClobber'",
errors,
writeInputToHost: true,
writeOutputToHost: true,
addToHistory: true).ConfigureAwait(false);

// There were errors installing PackageManagement.
if (errors.Length == 0)
{
_languageServer.Window.ShowMessage(new ShowMessageParams
{
Type = MessageType.Info,
Message = "PackageManagement updated, If you already had PackageManagement loaded in your session, please restart the PowerShell extension."
});
}
else
{
_languageServer.Window.ShowMessage(new ShowMessageParams
{
Type = MessageType.Error,
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`"
});
}
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,7 @@ public async Task<IEnumerable<TResult>> ExecuteCommandAsync<TResult>(
// cancelled prompt when it's called again.
if (executionOptions.AddToHistory)
{
this.PromptContext.AddToHistory(psCommand.Commands[0].CommandText);
this.PromptContext.AddToHistory(executionOptions.InputString ?? psCommand.Commands[0].CommandText);
}

bool hadErrors = false;
Expand Down Expand Up @@ -686,7 +686,7 @@ public async Task<IEnumerable<TResult>> ExecuteCommandAsync<TResult>(
if (executionOptions.WriteInputToHost)
{
this.WriteOutput(
psCommand.Commands[0].CommandText,
executionOptions.InputString ?? psCommand.Commands[0].CommandText,
includeNewLine: true);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ internal class ExecutionOptions
/// </summary>
public bool WriteInputToHost { get; set; }

/// <summary>
/// If this is set, we will use this string for history and writing to the host
/// instead of grabbing the command from the PSCommand.
/// </summary>
public string InputString { get; set; }

/// <summary>
/// Gets or sets a value indicating whether the command to
/// be executed is a console input prompt, such as the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ internal class LanguageServerSettings
private readonly object updateLock = new object();
public bool EnableProfileLoading { get; set; }

public bool PromptToUpdatePackageManagement { get; set; }

public ScriptAnalysisSettings ScriptAnalysis { get; set; }

public CodeFormattingSettings CodeFormatting { get; set; }
Expand All @@ -46,6 +48,7 @@ public void Update(
lock (updateLock)
{
this.EnableProfileLoading = settings.EnableProfileLoading;
this.PromptToUpdatePackageManagement = settings.PromptToUpdatePackageManagement;
this.ScriptAnalysis.Update(
settings.ScriptAnalysis,
workspaceRootPath,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1004,8 +1004,8 @@ await LanguageClient.SendRequest<EvaluateResponseBody>(
[Fact]
public async Task CanSendGetCommandRequest()
{
List<PSCommandMessage> pSCommandMessages =
await LanguageClient.SendRequest<List<PSCommandMessage>>("powerShell/getCommand", new GetCommandParams());
List<object> pSCommandMessages =
await LanguageClient.SendRequest<List<object>>("powerShell/getCommand", new GetCommandParams());

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

0 comments on commit 81a3801

Please sign in to comment.