Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PSReadLine integration (WIP) #671

Closed
Closed
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
8 changes: 8 additions & 0 deletions PowerShellEditorServices.build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -207,12 +207,20 @@ task LayoutModule -After Build {
Copy-Item -Force -Path $PSScriptRoot\src\PowerShellEditorServices\bin\$Configuration\netstandard1.6\publish\Serilog*.dll -Destination $PSScriptRoot\module\PowerShellEditorServices\bin\Core\

Copy-Item -Force -Path $PSScriptRoot\src\PowerShellEditorServices.Host\bin\$Configuration\netstandard1.6\* -Filter Microsoft.PowerShell.EditorServices*.dll -Destination $PSScriptRoot\module\PowerShellEditorServices\bin\Core\
if ($Configuration -eq 'Debug') {
Copy-Item -Force -Path $PSScriptRoot\src\PowerShellEditorServices.Host\bin\$Configuration\netstandard1.6\* -Filter Microsoft.PowerShell.EditorServices*.pdb -Destination $PSScriptRoot\module\PowerShellEditorServices\bin\Core\
}

Copy-Item -Force -Path $PSScriptRoot\src\PowerShellEditorServices.Host\bin\$Configuration\netstandard1.6\UnixConsoleEcho.dll -Destination $PSScriptRoot\module\PowerShellEditorServices\bin\Core\
Copy-Item -Force -Path $PSScriptRoot\src\PowerShellEditorServices.Host\bin\$Configuration\netstandard1.6\libdisablekeyecho.* -Destination $PSScriptRoot\module\PowerShellEditorServices\bin\Core\
if (!$script:IsUnix) {
Copy-Item -Force -Path $PSScriptRoot\src\PowerShellEditorServices\bin\$Configuration\net451\Serilog*.dll -Destination $PSScriptRoot\module\PowerShellEditorServices\bin\Desktop

Copy-Item -Force -Path $PSScriptRoot\src\PowerShellEditorServices.Host\bin\$Configuration\net451\* -Filter Microsoft.PowerShell.EditorServices*.dll -Destination $PSScriptRoot\module\PowerShellEditorServices\bin\Desktop\
if ($Configuration -eq 'Debug') {
Copy-Item -Force -Path $PSScriptRoot\src\PowerShellEditorServices.Host\bin\$Configuration\net451\* -Filter Microsoft.PowerShell.EditorServices*.pdb -Destination $PSScriptRoot\module\PowerShellEditorServices\bin\Desktop\
}

Copy-Item -Force -Path $PSScriptRoot\src\PowerShellEditorServices.Host\bin\$Configuration\net451\Newtonsoft.Json.dll -Destination $PSScriptRoot\module\PowerShellEditorServices\bin\Desktop\
Copy-Item -Force -Path $PSScriptRoot\src\PowerShellEditorServices.Host\bin\$Configuration\net451\UnixConsoleEcho.dll -Destination $PSScriptRoot\module\PowerShellEditorServices\bin\Desktop\
}
Expand Down
3 changes: 2 additions & 1 deletion module/PowerShellEditorServices/Start-EditorServices.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,8 @@ try {
-BundledModulesPath $BundledModulesPath `
-EnableConsoleRepl:$EnableConsoleRepl.IsPresent `
-DebugServiceOnly:$DebugServiceOnly.IsPresent `
-WaitForDebugger:$WaitForDebugger.IsPresent
-WaitForDebugger:$WaitForDebugger.IsPresent `
-FeatureFlags:$FeatureFlags

# TODO: Verify that the service is started
Log "Start-EditorServicesHost returned $editorServicesHost"
Expand Down
198 changes: 198 additions & 0 deletions module/Start-EditorServices.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
# PowerShell Editor Services Bootstrapper Script
# ----------------------------------------------
# This script contains startup logic for the PowerShell Editor Services
# module when launched by an editor. It handles the following tasks:
#
# - Verifying the existence of dependencies like PowerShellGet
# - Verifying that the expected version of the PowerShellEditorServices module is installed
# - Installing the PowerShellEditorServices module if confirmed by the user
# - Finding unused TCP port numbers for the language and debug services to use
# - Starting the language and debug services from the PowerShellEditorServices module
#
# NOTE: If editor integration authors make modifications to this
# script, please consider contributing changes back to the
# canonical version of this script at the PowerShell Editor
# Services GitHub repository:
#
# https://github.com/PowerShell/PowerShellEditorServices/blob/master/module/Start-EditorServices.ps1

param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$EditorServicesVersion,

[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$HostName,

[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$HostProfileId,

[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$HostVersion,

[ValidateNotNullOrEmpty()]
[string]
$BundledModulesPath,

[ValidateNotNullOrEmpty()]
$LogPath,

[ValidateSet("Normal", "Verbose", "Error","Diagnostic")]
$LogLevel,

[string[]]
$FeatureFlags = @(),

[switch]
$WaitForDebugger,

[switch]
$ConfirmInstall
)

# This variable will be assigned later to contain information about
# what happened while attempting to launch the PowerShell Editor
# Services host
$resultDetails = $null;

function Test-ModuleAvailable($ModuleName, $ModuleVersion) {
$modules = Get-Module -ListAvailable $moduleName
if ($modules -ne $null) {
if ($ModuleVersion -ne $null) {
foreach ($module in $modules) {
if ($module.Version.Equals($moduleVersion)) {
return $true;
}
}
}
else {
return $true;
}
}

return $false;
}

function Test-PortAvailability($PortNumber) {
$portAvailable = $true;

try {
$ipAddress = [System.Net.Dns]::GetHostEntryAsync("localhost").Result.AddressList[0];
$tcpListener = [System.Net.Sockets.TcpListener]::new($ipAddress, $portNumber);
$tcpListener.Start();
$tcpListener.Stop();

}
catch [System.Net.Sockets.SocketException] {
# Check the SocketErrorCode to see if it's the expected exception
if ($error[0].Exception.InnerException.SocketErrorCode -eq [System.Net.Sockets.SocketError]::AddressAlreadyInUse) {
$portAvailable = $false;
}
else {
Write-Output ("Error code: " + $error[0].SocketErrorCode)
}
}

return $portAvailable;
}

$rand = [System.Random]::new()
function Get-AvailablePort {
$triesRemaining = 10;

while ($triesRemaining -gt 0) {
$port = $rand.Next(10000, 30000)
if ((Test-PortAvailability -PortAvailability $port) -eq $true) {
return $port
}

$triesRemaining--;
}

return $null
}

# OUTPUT PROTOCOL
# - "started 29981 39898" - Server(s) are started, language and debug server ports (respectively)
# - "failed Error message describing the failure" - General failure while starting, show error message to user (?)
# - "needs_install" - User should be prompted to install PowerShell Editor Services via the PowerShell Gallery

# Add BundledModulesPath to $env:PSModulePath
if ($BundledModulesPath) {
$env:PSMODULEPATH = $BundledModulesPath + [System.IO.Path]::PathSeparator + $env:PSMODULEPATH
}

# Check if PowerShellGet module is available
if ((Test-ModuleAvailable "PowerShellGet") -eq $false) {
# TODO: WRITE ERROR
}

# Check if the expected version of the PowerShell Editor Services
# module is installed
$parsedVersion = [System.Version]::new($EditorServicesVersion)
if ((Test-ModuleAvailable "PowerShellEditorServices" -RequiredVersion $parsedVersion) -eq $false) {
if ($ConfirmInstall) {
# TODO: Check for error and return failure if necessary
Install-Module "PowerShellEditorServices" -RequiredVersion $parsedVersion -Confirm
}
else {
# Indicate to the client that the PowerShellEditorServices module
# needs to be installed
Write-Output "needs_install"
}
}

Import-Module PowerShellEditorServices -RequiredVersion $parsedVersion -ErrorAction Stop

# Locate available port numbers for services
$languageServicePort = Get-AvailablePort
$debugServicePort = Get-AvailablePort

$editorServicesHost =
Start-EditorServicesHost `
-HostName $HostName `
-HostProfileId $HostProfileId `
-HostVersion $HostVersion `
-LogPath $LogPath `
-LogLevel $LogLevel `
-AdditionalModules @() `
-LanguageServicePort $languageServicePort `
-DebugServicePort $debugServicePort `
-BundledModulesPath $BundledModulesPath `
-WaitForDebugger:$WaitForDebugger.IsPresent `
-FeatureFlags $FeatureFlags

# TODO: Verify that the service is started

$resultDetails = @{
"status" = "started";
"channel" = "tcp";
"languageServicePort" = $languageServicePort;
"debugServicePort" = $debugServicePort;
};

# Notify the client that the services have started
Write-Output (ConvertTo-Json -InputObject $resultDetails -Compress)

try {
# Wait for the host to complete execution before exiting
$editorServicesHost.WaitForCompletion()
}
catch [System.Exception] {
$e = $_.Exception; #.InnerException;
$errorString = ""

while ($e -ne $null) {
$errorString = $errorString + ($e.Message + "`r`n" + $e.StackTrace + "`r`n")
$e = $e.InnerException;
}

Write-Error ("`r`nCaught error while waiting for EditorServicesHost to complete:`r`n" + $errorString)
}
6 changes: 4 additions & 2 deletions src/PowerShellEditorServices.Host/EditorServicesHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ private EditorSession CreateSession(
bool enableConsoleRepl)
{
EditorSession editorSession = new EditorSession(this.logger);
PowerShellContext powerShellContext = new PowerShellContext(this.logger);
PowerShellContext powerShellContext = new PowerShellContext(this.logger, this.featureFlags.Contains("PSReadLine"));

EditorServicesPSHostUserInterface hostUserInterface =
enableConsoleRepl
Expand Down Expand Up @@ -407,7 +407,9 @@ private EditorSession CreateDebugSession(
bool enableConsoleRepl)
{
EditorSession editorSession = new EditorSession(this.logger);
PowerShellContext powerShellContext = new PowerShellContext(this.logger);
PowerShellContext powerShellContext = new PowerShellContext(
this.logger,
this.featureFlags.Contains("PSReadLine"));

EditorServicesPSHostUserInterface hostUserInterface =
enableConsoleRepl
Expand Down
30 changes: 27 additions & 3 deletions src/PowerShellEditorServices.Protocol/Server/DebugAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,17 @@ protected Task LaunchScript(RequestContext<object> requestContext)

private async Task OnExecutionCompleted(Task executeTask)
{
try
{
await executeTask;
}
catch (Exception e)
{
Logger.Write(
LogLevel.Error,
"Exception occurred while awaiting debug launch task.\n\n" + e.ToString());
}

Logger.Write(LogLevel.Verbose, "Execution completed, terminating...");

this.executionCompleted = true;
Expand Down Expand Up @@ -471,7 +482,7 @@ protected async Task HandleDisconnectRequest(
if (this.executionCompleted == false)
{
this.disconnectRequestContext = requestContext;
this.editorSession.PowerShellContext.AbortExecution();
this.editorSession.PowerShellContext.AbortExecution(shouldAbortDebugSession: true);

if (this.isInteractiveDebugSession)
{
Expand Down Expand Up @@ -756,6 +767,20 @@ protected async Task HandleStackTraceRequest(
StackFrameDetails[] stackFrames =
editorSession.DebugService.GetStackFrames();

// Handle a rare race condition where the adapter requests stack frames before they've
// begun building.
if (stackFrames == null)
{
await requestContext.SendResult(
new StackTraceResponseBody
{
StackFrames = new StackFrame[0],
TotalFrames = 0
});

return;
}

List<StackFrame> newStackFrames = new List<StackFrame>();

int startFrameIndex = stackTraceParams.StartFrame ?? 0;
Expand All @@ -779,8 +804,7 @@ protected async Task HandleStackTraceRequest(
i));
}

await requestContext.SendResult(
new StackTraceResponseBody
await requestContext.SendResult( new StackTraceResponseBody
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Mistake, must have done a vim line join and didn't notice.

{
StackFrames = newStackFrames.ToArray(),
TotalFrames = newStackFrames.Count
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1489,6 +1489,15 @@ private static async Task DelayThenInvokeDiagnostics(
catch (TaskCanceledException)
{
// If the task is cancelled, exit directly
foreach (var script in filesToAnalyze)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Comment needs to be updated.

{
await PublishScriptDiagnostics(
script,
script.SyntaxMarkers,
correctionIndex,
eventSender);
}

return;
}

Expand Down
Loading