Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/PowerShellEditorServices/Server/PsesLanguageServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ public async Task StartAsync()
.WithHandler<GetCommentHelpHandler>()
.WithHandler<EvaluateHandler>()
.WithHandler<GetCommandHandler>()
.WithHandler<GetModuleHandler>()
.WithHandler<ShowHelpHandler>()
.WithHandler<ExpandAliasHandler>()
.WithHandler<PsesSemanticTokensHandler>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
Expand All @@ -14,7 +16,37 @@ namespace Microsoft.PowerShell.EditorServices.Handlers
[Serial, Method("powerShell/getCommand", Direction.ClientToServer)]
internal interface IGetCommandHandler : IJsonRpcRequestHandler<GetCommandParams, List<PSCommandMessage>> { }

internal class GetCommandParams : IRequest<List<PSCommandMessage>> { }
internal class GetCommandParams : IRequest<List<PSCommandMessage>>
{
/// <summary>
/// An optional name (supports wildcards) to scope the returned commands.
/// When omitted, all commands are returned.
/// </summary>
public string Name { get; set; }

/// <summary>
/// An optional module name (supports wildcards) to scope the returned
/// commands. When omitted, commands from all modules are returned.
/// </summary>
public string Module { get; set; }

/// <summary>
/// When true, the expensive parameter and parameter-set metadata is not
/// resolved or returned. Callers that only need command names and modules
/// (such as the Command Explorer tree) should set this to avoid the large
/// serialization cost of the full command table.
/// </summary>
public bool ExcludeParameters { get; set; }

/// <summary>
/// When true, module-less functions and scripts that PowerShell's default
/// session provides (e.g. cd.., prompt, TabExpansion2) are omitted. These
/// are interactive shell conveniences and engine plumbing rather than
/// commands a user authored or imported, so the Command Explorer hides them.
/// Module-provided commands (including built-in modules) are never affected.
/// </summary>
public bool ExcludeDefaultFunctions { get; set; }
}

/// <summary>
/// Describes the message to get the details for a single PowerShell Command
Expand All @@ -24,6 +56,7 @@ internal class PSCommandMessage
{
public string Name { get; set; }
public string ModuleName { get; set; }
public string ModuleVersion { get; set; }
public string DefaultParameterSet { get; set; }
public Dictionary<string, ParameterMetadata> Parameters { get; set; }
public System.Collections.ObjectModel.ReadOnlyCollection<CommandParameterSetInfo> ParameterSets { get; set; }
Expand All @@ -39,11 +72,28 @@ public async Task<List<PSCommandMessage>> Handle(GetCommandParams request, Cance
{
PSCommand psCommand = new();

// Executes the following:
// Get-Command -CommandType Function,Cmdlet,ExternalScript | Sort-Object -Property Name
// Executes the following, scoping by name and/or module when provided
// so we don't serialize the entire command table (which is expensive):
// Get-Command -CommandType Function,Cmdlet,ExternalScript [-Name <name>] [-Module <module>] | Sort-Object -Property Name
psCommand
.AddCommand(@"Microsoft.PowerShell.Core\Get-Command")
.AddParameter("CommandType", new[] { "Function", "Cmdlet", "ExternalScript" })
.AddParameter("CommandType", new[] { "Function", "Cmdlet", "ExternalScript" });

if (!string.IsNullOrEmpty(request.Name))
{
psCommand.AddParameter("Name", request.Name);
}

if (!string.IsNullOrEmpty(request.Module))
{
psCommand.AddParameter("Module", request.Module);
}

// A name or module filter that matches nothing writes a non-terminating
// error; ignore it so we simply return an empty list instead.
psCommand.AddParameter("ErrorAction", "Ignore");

psCommand
.AddCommand(@"Microsoft.PowerShell.Utility\Sort-Object")
.AddParameter("Property", "Name");

Expand All @@ -54,6 +104,39 @@ public async Task<List<PSCommandMessage>> Handle(GetCommandParams request, Cance
{
foreach (CommandInfo command in result)
{
// Skip commands injected by the editor's terminal integration
// (the PSES host's fake PSConsoleHostReadLine and VS Code's
// shell-integration helpers); they are implementation details,
// not real commands the user authored or imported.
if (IsEditorInjectedCommand(command))
{
continue;
}

// Optionally drop PowerShell's default-session shell functions
// (and the install's profile-resource script), which are
// module-less and not meaningful in the command list.
if (request.ExcludeDefaultFunctions
&& IsDefaultSessionFunction(command))
{
continue;
}

// When only names/modules are requested, skip resolving the
// parameter metadata entirely. Accessing Parameters/ParameterSets
// forces PowerShell to compute (and we then serialize) the full
// metadata, which is the dominant cost for the whole command table.
if (request.ExcludeParameters)
{
commandList.Add(new PSCommandMessage
{
Name = command.Name,
ModuleName = command.ModuleName,
ModuleVersion = command.Version?.ToString()
});
continue;
}

// Some info objects have a quicker way to get the DefaultParameterSet. These
// are also the most likely to show up so win-win.
string defaultParameterSet = null;
Expand Down Expand Up @@ -84,6 +167,7 @@ public async Task<List<PSCommandMessage>> Handle(GetCommandParams request, Cance
{
Name = command.Name,
ModuleName = command.ModuleName,
ModuleVersion = command.Version?.ToString(),
Parameters = command.Parameters,
ParameterSets = command.ParameterSets,
DefaultParameterSet = defaultParameterSet
Expand All @@ -93,5 +177,74 @@ public async Task<List<PSCommandMessage>> Handle(GetCommandParams request, Cance

return commandList;
}

// Names of helper functions injected by VS Code's terminal shell
// integration script (shellIntegration.ps1), which the PSES host executes.
// These are editor plumbing rather than user- or module-provided commands.
private static readonly HashSet<string> s_shellIntegrationFunctions = new(System.StringComparer.OrdinalIgnoreCase)
{
"__VSCode-Escape-Value",
"Set-MappedKeyHandler",
"Set-MappedKeyHandlers"
};

// Identifies commands injected by the editor's terminal integration that
// should not be surfaced as real commands.
private static bool IsEditorInjectedCommand(CommandInfo command)
{
if (command.CommandType != CommandTypes.Function)
{
return false;
}

// The fake global PSConsoleHostReadLine function that the PSES host
// defines for terminal shell integration (see PsesInternalHost.cs) has
// no real version, whereas the genuine PSReadLine export always reports
// a real version, so that export is never matched here.
if (command.Name == "PSConsoleHostReadLine"
Comment thread
andyleejordan marked this conversation as resolved.
&& (command.Version is null
|| (command.Version.Major == 0
&& command.Version.Minor == 0
&& command.Version.Build <= 0
&& command.Version.Revision <= 0)))
{
return true;
}

return s_shellIntegrationFunctions.Contains(command.Name);
}

// The names of the functions that PowerShell's default session state
// provides (cd.., cd\, cd~, Clear-Host, exec, help, oss, Pause, prompt,
// TabExpansion2). Enumerated once from InitialSessionState so the list stays
// correct across PowerShell versions rather than being hard-coded.
private static readonly System.Lazy<HashSet<string>> s_defaultSessionFunctions = new(() =>
new HashSet<string>(
InitialSessionState.CreateDefault2().Commands
.OfType<SessionStateFunctionEntry>()
.Select(static entry => entry.Name),
System.StringComparer.OrdinalIgnoreCase));

// Identifies module-less functions and scripts that PowerShell's default
// session provides — interactive shell conveniences and engine plumbing that
// aren't meaningful in the command list. Only matches commands with no module,
// so a module-provided command (including built-in modules) is never affected.
private static bool IsDefaultSessionFunction(CommandInfo command)
{
if (!string.IsNullOrEmpty(command.ModuleName))
{
return false;
}

// The profile-resource script shipped alongside the PowerShell install
// (e.g. pwsh.profile.resource.ps1) is install plumbing, not a user script.
if (command.CommandType == CommandTypes.ExternalScript)
{
return command.Name.StartsWith("pwsh.profile.resource", System.StringComparison.OrdinalIgnoreCase);
}

return command.CommandType == CommandTypes.Function
&& s_defaultSessionFunctions.Value.Contains(command.Name);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Management.Automation;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using OmniSharp.Extensions.JsonRpc;
using Microsoft.PowerShell.EditorServices.Services.PowerShell;
using Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution;

namespace Microsoft.PowerShell.EditorServices.Handlers
{
[Serial, Method("powerShell/getModule", Direction.ClientToServer)]
internal interface IGetModuleHandler : IJsonRpcRequestHandler<GetModuleParams, PSModuleMessage> { }
Comment thread
andyleejordan marked this conversation as resolved.

internal class GetModuleParams : IRequest<PSModuleMessage>
{
/// <summary>
/// The name of the module to retrieve metadata for.
/// </summary>
public string Name { get; set; }

/// <summary>
/// An optional specific version of the module. When omitted, the newest
/// available version is returned.
/// </summary>
public string Version { get; set; }
}

/// <summary>
/// Describes the metadata for a single PowerShell module, used to populate
/// the Command Explorer's module tooltips.
/// </summary>
internal class PSModuleMessage
{
public string Name { get; set; }
public string Version { get; set; }
public string Description { get; set; }
public string Path { get; set; }
public string Author { get; set; }
public string CompanyName { get; set; }
public string ProjectUri { get; set; }
public string PowerShellVersion { get; set; }
}

internal class GetModuleHandler : IGetModuleHandler
{
private readonly IInternalPowerShellExecutionService _executionService;

public GetModuleHandler(IInternalPowerShellExecutionService executionService) => _executionService = executionService;

public async Task<PSModuleMessage> Handle(GetModuleParams request, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(request.Name))
{
return null;
}

// Resolve a module's metadata from the available modules, pinning to a
// specific version when requested and otherwise taking the newest.
const string GetModuleScript = @"
[System.Diagnostics.DebuggerHidden()]
[CmdletBinding()]
param (
[String]$Name,
[String]$Version
)
$modules = Microsoft.PowerShell.Core\Get-Module -ListAvailable -Name $Name -ErrorAction Ignore
if ($Version) {
$modules = $modules | Microsoft.PowerShell.Core\Where-Object { $_.Version.ToString() -eq $Version }
}
$module = $modules | Microsoft.PowerShell.Utility\Sort-Object Version -Descending | Microsoft.PowerShell.Utility\Select-Object -First 1
if ($null -eq $module) {
return
}
[PSCustomObject]@{
Name = $module.Name
Version = $module.Version.ToString()
Description = $module.Description
Path = $module.Path
Author = $module.Author
CompanyName = $module.CompanyName
ProjectUri = if ($module.ProjectUri) { $module.ProjectUri.ToString() } else { '' }
PowerShellVersion = if ($module.PowerShellVersion) { $module.PowerShellVersion.ToString() } else { '' }
}
";
Comment on lines +64 to +88

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@SeeminglyScience main thing I'd like your eye on.


PSCommand getModuleCommand = new PSCommand()
.AddScript(GetModuleScript, useLocalScope: true)
.AddParameter("Name", request.Name)
.AddParameter("Version", request.Version);

IReadOnlyList<PSObject> results = await _executionService.ExecutePSCommandAsync<PSObject>(
getModuleCommand,
cancellationToken,
new PowerShellExecutionOptions
{
ThrowOnError = false
}).ConfigureAwait(false);

PSObject result = results is { Count: > 0 } ? results[0] : null;
if (result is null)
{
return null;
}

return new PSModuleMessage
{
Name = GetPropertyString(result, "Name"),
Version = GetPropertyString(result, "Version"),
Description = GetPropertyString(result, "Description"),
Path = GetPropertyString(result, "Path"),
Author = GetPropertyString(result, "Author"),
CompanyName = GetPropertyString(result, "CompanyName"),
ProjectUri = GetPropertyString(result, "ProjectUri"),
PowerShellVersion = GetPropertyString(result, "PowerShellVersion")
};
}

private static string GetPropertyString(PSObject psObject, string propertyName)
=> psObject.Properties[propertyName]?.Value as string ?? string.Empty;
}
}
Loading
Loading