Skip to content

Commit f93653b

Browse files
authored
Code cleanup of the start script and ESHost.cs file (#796)
* Code cleanup of the start script and ESHost.cs file Address some PSSA warnings, version guard access to $Is<platforms> vars, rename Test-NamedPipeName-OrCreate-IfNull to Get-ValidatedNamedPipeName. Not 100% sold on the new name so open to suggestions. * Address PR feedback - remove redundant version checking, add comment * Address PR feedback - use parameter labels and named parameters
1 parent 487ad1d commit f93653b

File tree

2 files changed

+65
-47
lines changed

2 files changed

+65
-47
lines changed

module/PowerShellEditorServices/Start-EditorServices.ps1

+52-43
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,27 @@
1-
# PowerShell Editor Services Bootstrapper Script
2-
# ----------------------------------------------
3-
# This script contains startup logic for the PowerShell Editor Services
4-
# module when launched by an editor. It handles the following tasks:
5-
#
6-
# - Verifying the existence of dependencies like PowerShellGet
7-
# - Verifying that the expected version of the PowerShellEditorServices module is installed
8-
# - Installing the PowerShellEditorServices module if confirmed by the user
9-
# - Creating named pipes for the language and debug services to use (if using named pipes)
10-
# - Starting the language and debug services from the PowerShellEditorServices module
11-
#
12-
# NOTE: If editor integration authors make modifications to this
13-
# script, please consider contributing changes back to the
14-
# canonical version of this script at the PowerShell Editor
15-
# Services GitHub repository:
16-
#
17-
# https://github.com/PowerShell/PowerShellEditorServices/blob/master/module/PowerShellEditorServices/Start-EditorServices.ps1
1+
<#
2+
.SYNOPSIS
3+
Starts the language and debug services from the PowerShellEditorServices module.
4+
.DESCRIPTION
5+
PowerShell Editor Services Bootstrapper Script
6+
----------------------------------------------
7+
This script contains startup logic for the PowerShell Editor Services
8+
module when launched by an editor. It handles the following tasks:
9+
10+
- Verifying the existence of dependencies like PowerShellGet
11+
- Verifying that the expected version of the PowerShellEditorServices module is installed
12+
- Installing the PowerShellEditorServices module if confirmed by the user
13+
- Creating named pipes for the language and debug services to use (if using named pipes)
14+
- Starting the language and debug services from the PowerShellEditorServices module
15+
.INPUTS
16+
None
17+
.OUTPUTS
18+
None
19+
.NOTES
20+
If editor integration authors make modifications to this script, please
21+
consider contributing changes back to the canonical version of this script
22+
at the PowerShell Editor Services GitHub repository:
23+
https://github.com/PowerShell/PowerShellEditorServices/blob/master/module/PowerShellEditorServices/Start-EditorServices.ps1'
24+
#>
1825
[CmdletBinding(DefaultParameterSetName="NamedPipe")]
1926
param(
2027
[Parameter(Mandatory=$true)]
@@ -65,7 +72,7 @@ param(
6572
[switch]
6673
$ConfirmInstall,
6774

68-
[Parameter(ParameterSetName="Stdio",Mandatory=$true)]
75+
[Parameter(ParameterSetName="Stdio", Mandatory=$true)]
6976
[switch]
7077
$Stdio,
7178

@@ -154,9 +161,6 @@ if ($host.Runspace.LanguageMode -eq 'ConstrainedLanguage') {
154161
ExitWithError "PowerShell is configured with an unsupported LanguageMode (ConstrainedLanguage), language features are disabled."
155162
}
156163

157-
# Are we running in PowerShell 5 or later?
158-
$isPS5orLater = $PSVersionTable.PSVersion.Major -ge 5
159-
160164
# If PSReadline is present in the session, remove it so that runspace
161165
# management is easier
162166
if ((Microsoft.PowerShell.Core\Get-Module PSReadline).Count -gt 0) {
@@ -173,8 +177,8 @@ function Test-ModuleAvailable($ModuleName, $ModuleVersion) {
173177
Log "Testing module availability $ModuleName $ModuleVersion"
174178

175179
$modules = Microsoft.PowerShell.Core\Get-Module -ListAvailable $moduleName
176-
if ($modules -ne $null) {
177-
if ($ModuleVersion -ne $null) {
180+
if ($null -ne $modules) {
181+
if ($null -ne $ModuleVersion) {
178182
foreach ($module in $modules) {
179183
if ($module.Version.Equals($moduleVersion)) {
180184
Log "$ModuleName $ModuleVersion found"
@@ -193,7 +197,6 @@ function Test-ModuleAvailable($ModuleName, $ModuleVersion) {
193197
}
194198

195199
function New-NamedPipeName {
196-
197200
# We try 10 times to find a valid pipe name
198201
for ($i = 0; $i -lt 10; $i++) {
199202
$PipeName = "PSES_$([System.IO.Path]::GetRandomFileName())"
@@ -202,6 +205,7 @@ function New-NamedPipeName {
202205
return $PipeName
203206
}
204207
}
208+
205209
ExitWithError "Could not find valid a pipe name."
206210
}
207211

@@ -213,15 +217,14 @@ function Get-NamedPipePath {
213217
$PipeName
214218
)
215219

216-
if (-not $IsLinux -and -not $IsMacOS) {
220+
if (($PSVersionTable.PSVersion.Major -le 5) -or $IsWindows) {
217221
return "\\.\pipe\$PipeName";
218222
}
219223
else {
220224
# Windows uses NamedPipes where non-Windows platforms use Unix Domain Sockets.
221225
# the Unix Domain Sockets live in the tmp directory and are prefixed with "CoreFxPipe_"
222226
return (Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "CoreFxPipe_$PipeName")
223227
}
224-
225228
}
226229

227230
# Returns True if it's a valid pipe name
@@ -236,7 +239,7 @@ function Test-NamedPipeName {
236239
)
237240

238241
$path = Get-NamedPipePath -PipeName $PipeName
239-
return -not (Test-Path $path)
242+
return !(Test-Path $path)
240243
}
241244

242245
function Set-NamedPipeMode {
@@ -247,7 +250,7 @@ function Set-NamedPipeMode {
247250
$PipeFile
248251
)
249252

250-
if ($IsWindows) {
253+
if (($PSVersionTable.PSVersion.Major -le 5) -or $IsWindows) {
251254
return
252255
}
253256

@@ -268,33 +271,37 @@ function Set-NamedPipeMode {
268271
LogSection "Console Encoding"
269272
Log $OutputEncoding
270273

271-
function Test-NamedPipeName-OrCreate-IfNull {
274+
function Get-ValidatedNamedPipeName {
272275
param(
273276
[string]
274277
$PipeName
275278
)
276-
if (-not $PipeName) {
279+
280+
# If no PipeName is passed in, then we create one that's guaranteed to be valid
281+
if (!$PipeName) {
277282
$PipeName = New-NamedPipeName
278283
}
279-
else {
280-
if (-not (Test-NamedPipeName -PipeName $PipeName)) {
281-
ExitWithError "Pipe name supplied is already taken: $PipeName"
282-
}
284+
elseif (!(Test-NamedPipeName -PipeName $PipeName)) {
285+
ExitWithError "Pipe name supplied is already in use: $PipeName"
283286
}
287+
284288
return $PipeName
285289
}
286290

287291
function Set-PipeFileResult {
288292
param (
289293
[Hashtable]
290294
$ResultTable,
295+
291296
[string]
292297
$PipeNameKey,
298+
293299
[string]
294300
$PipeNameValue
295301
)
302+
296303
$ResultTable[$PipeNameKey] = Get-NamedPipePath -PipeName $PipeNameValue
297-
if ($IsLinux -or $IsMacOS) {
304+
if (($PSVersionTable.PSVersion.Major -ge 6) -and ($IsLinux -or $IsMacOS)) {
298305
Set-NamedPipeMode -PipeFile $ResultTable[$PipeNameKey]
299306
}
300307
}
@@ -349,11 +356,12 @@ try {
349356
-WaitForDebugger:$WaitForDebugger.IsPresent
350357
break
351358
}
359+
352360
"NamedPipeSimplex" {
353-
$LanguageServiceInPipeName = Test-NamedPipeName-OrCreate-IfNull $LanguageServiceInPipeName
354-
$LanguageServiceOutPipeName = Test-NamedPipeName-OrCreate-IfNull $LanguageServiceOutPipeName
355-
$DebugServiceInPipeName = Test-NamedPipeName-OrCreate-IfNull $DebugServiceInPipeName
356-
$DebugServiceOutPipeName = Test-NamedPipeName-OrCreate-IfNull $DebugServiceOutPipeName
361+
$LanguageServiceInPipeName = Get-ValidatedNamedPipeName $LanguageServiceInPipeName
362+
$LanguageServiceOutPipeName = Get-ValidatedNamedPipeName $LanguageServiceOutPipeName
363+
$DebugServiceInPipeName = Get-ValidatedNamedPipeName $DebugServiceInPipeName
364+
$DebugServiceOutPipeName = Get-ValidatedNamedPipeName $DebugServiceOutPipeName
357365

358366
$editorServicesHost = Start-EditorServicesHost `
359367
-HostName $HostName `
@@ -377,9 +385,10 @@ try {
377385
Set-PipeFileResult $resultDetails "debugServiceWritePipeName" $DebugServiceOutPipeName
378386
break
379387
}
388+
380389
Default {
381-
$LanguageServicePipeName = Test-NamedPipeName-OrCreate-IfNull $LanguageServicePipeName
382-
$DebugServicePipeName = Test-NamedPipeName-OrCreate-IfNull $DebugServicePipeName
390+
$LanguageServicePipeName = Get-ValidatedNamedPipeName $LanguageServicePipeName
391+
$DebugServicePipeName = Get-ValidatedNamedPipeName $DebugServicePipeName
383392

384393
$editorServicesHost = Start-EditorServicesHost `
385394
-HostName $HostName `
@@ -417,7 +426,7 @@ catch [System.Exception] {
417426

418427
Log "ERRORS caught starting up EditorServicesHost"
419428

420-
while ($e -ne $null) {
429+
while ($null -ne $e) {
421430
$errorString = $errorString + ($e.Message + "`r`n" + $e.StackTrace + "`r`n")
422431
$e = $e.InnerException;
423432
Log $errorString
@@ -438,7 +447,7 @@ catch [System.Exception] {
438447

439448
Log "ERRORS caught while waiting for EditorServicesHost to complete execution"
440449

441-
while ($e -ne $null) {
450+
while ($null -ne $e) {
442451
$errorString = $errorString + ($e.Message + "`r`n" + $e.StackTrace + "`r`n")
443452
$e = $e.InnerException;
444453
Log $errorString

src/PowerShellEditorServices.Host/EditorServicesHost.cs

+13-4
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,11 @@ public class EditorServiceTransportConfig
4545
/// For NamedPipe it's the pipe name.
4646
/// </summary>
4747
public string InOutPipeName { get; set; }
48+
4849
public string OutPipeName { get; set; }
50+
4951
public string InPipeName { get; set; }
52+
5053
internal string Endpoint => OutPipeName != null && InPipeName != null ? $"In pipe: {InPipeName} Out pipe: {OutPipeName}" : $" InOut pipe: {InOutPipeName}";
5154
}
5255

@@ -242,10 +245,15 @@ await this.editorSession.PowerShellContext.ImportCommandsModule(
242245
// gets initialized when that is done earlier than LanguageServer.Initialize
243246
foreach (string module in this.additionalModules)
244247
{
248+
var command =
249+
new System.Management.Automation.PSCommand()
250+
.AddCommand("Microsoft.PowerShell.Core\\Import-Module")
251+
.AddParameter("Name", module);
252+
245253
await this.editorSession.PowerShellContext.ExecuteCommand<System.Management.Automation.PSObject>(
246-
new System.Management.Automation.PSCommand().AddCommand("Import-Module").AddArgument(module),
247-
false,
248-
true);
254+
command,
255+
sendOutputToHost: false,
256+
sendErrorToHost: true);
249257
}
250258

251259
protocolEndpoint.Start();
@@ -455,6 +463,7 @@ private void CurrentDomain_UnhandledException(
455463
e.ExceptionObject.ToString()));
456464
}
457465
#endif
466+
458467
private IServerListener CreateServiceListener(MessageProtocolType protocol, EditorServiceTransportConfig config)
459468
{
460469
switch (config.TransportType)
@@ -466,7 +475,7 @@ private IServerListener CreateServiceListener(MessageProtocolType protocol, Edit
466475

467476
case EditorServiceTransportType.NamedPipe:
468477
{
469-
if (config.OutPipeName !=null && config.InPipeName !=null)
478+
if ((config.OutPipeName != null) && (config.InPipeName != null))
470479
{
471480
this.logger.Write(LogLevel.Verbose, $"Creating NamedPipeServerListener for ${protocol} protocol with two pipes: In: '{config.InPipeName}'. Out: '{config.OutPipeName}'");
472481
return new NamedPipeServerListener(protocol, config.InPipeName, config.OutPipeName, this.logger);

0 commit comments

Comments
 (0)