Skip to content

Update ExpandAliasHandler to use latest PowerShell parser #2108

Open
@andyleejordan

Description

@andyleejordan

Prerequisites

  • I have written a descriptive issue title.
  • I have searched all issues to ensure it has not already been requested.

Summary

In the following code we (repeatedly) define an internal PowerShell script that uses the original parser to expand the alias.

public async Task<ExpandAliasResult> Handle(ExpandAliasParams request, CancellationToken cancellationToken)
{
const string script = @"
function __Expand-Alias {
[System.Diagnostics.DebuggerHidden()]
param($targetScript)
[ref]$errors=$null
$tokens = [System.Management.Automation.PsParser]::Tokenize($targetScript, $errors).Where({$_.type -eq 'command'}) |
Sort-Object Start -Descending
foreach ($token in $tokens) {
$definition=(Get-Command ('`'+$token.Content) -CommandType Alias -ErrorAction SilentlyContinue).Definition
if($definition) {
$lhs=$targetScript.Substring(0, $token.Start)
$rhs=$targetScript.Substring($token.Start + $token.Length)
$targetScript=$lhs + $definition + $rhs
}
}
$targetScript
}";
// TODO: Refactor to not rerun the function definition every time.
PSCommand psCommand = new();
psCommand
.AddScript(script)
.AddStatement()
.AddCommand("__Expand-Alias")
.AddArgument(request.Text);
System.Collections.Generic.IReadOnlyList<string> result = await _executionService.ExecutePSCommandAsync<string>(psCommand, cancellationToken).ConfigureAwait(false);
return new ExpandAliasResult
{
Text = result[0]
};
}

Proposed Design

This should be updated to use the new parser directly from the PowerShell APIs in C# and return a proper edit (potentially deprecating the need for an entirely separate custom request).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions