Skip to content

Load only bundled PSReadLine #1514

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

Merged
merged 7 commits into from
Jul 1, 2021
Merged
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 PowerShellEditorServices.Common.props
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/PowerShell/PowerShellEditorServices</RepositoryUrl>
<DebugType>portable</DebugType>
<DefineConstants Condition=" '$(ExtraDefineConstants)' != '' ">$(DefineConstants);$(ExtraDefineConstants)</DefineConstants>
</PropertyGroup>
</Project>
10 changes: 5 additions & 5 deletions PowerShellEditorServices.build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -259,20 +259,20 @@ task TestServer TestServerWinPS,TestServerPS7,TestServerPS72

task TestServerWinPS -If (-not $script:IsNix) {
Set-Location .\test\PowerShellEditorServices.Test\
exec { & $script:dotnetExe test --logger trx -f $script:NetRuntime.Desktop (DotNetTestFilter) }
exec { & $script:dotnetExe test -p:ExtraDefineConstants=TEST --logger trx -f $script:NetRuntime.Desktop (DotNetTestFilter) }
}

task TestServerPS7 -If (-not $script:IsRosetta) {
Set-Location .\test\PowerShellEditorServices.Test\
Invoke-WithCreateDefaultHook -NewModulePath $script:PSCoreModulePath {
exec { & $script:dotnetExe test --logger trx -f $script:NetRuntime.PS7 (DotNetTestFilter) }
exec { & $script:dotnetExe test -p:ExtraDefineConstants=TEST --logger trx -f $script:NetRuntime.PS7 (DotNetTestFilter) }
}
}

task TestServerPS72 {
Set-Location .\test\PowerShellEditorServices.Test\
Invoke-WithCreateDefaultHook -NewModulePath $script:PSCoreModulePath {
exec { & $script:dotnetExe test --logger trx -f $script:NetRuntime.PS72 (DotNetTestFilter) }
exec { & $script:dotnetExe test -p:ExtraDefineConstants=TEST --logger trx -f $script:NetRuntime.PS72 (DotNetTestFilter) }
}
}

Expand All @@ -281,13 +281,13 @@ task TestE2E {

$env:PWSH_EXE_NAME = if ($IsCoreCLR) { "pwsh" } else { "powershell" }
$NetRuntime = if ($IsRosetta) { $script:NetRuntime.PS72 } else { $script:NetRuntime.PS7 }
exec { & $script:dotnetExe test --logger trx -f $NetRuntime (DotNetTestFilter) }
exec { & $script:dotnetExe test -p:ExtraDefineConstants=TEST --logger trx -f $NetRuntime (DotNetTestFilter) }

# Run E2E tests in ConstrainedLanguage mode.
if (!$script:IsNix) {
try {
[System.Environment]::SetEnvironmentVariable("__PSLockdownPolicy", "0x80000007", [System.EnvironmentVariableTarget]::Machine);
exec { & $script:dotnetExe test --logger trx -f $script:NetRuntime.PS7 (DotNetTestFilter) }
exec { & $script:dotnetExe test -p:ExtraDefineConstants=TEST --logger trx -f $script:NetRuntime.PS7 (DotNetTestFilter) }
} finally {
[System.Environment]::SetEnvironmentVariable("__PSLockdownPolicy", $null, [System.EnvironmentVariableTarget]::Machine);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,21 +296,6 @@ public static Runspace CreateRunspace(PSHost psHost, PSLanguageMode languageMode
return runspace;
}

/// <summary>
/// Initializes a new instance of the PowerShellContext class using
/// an existing runspace for the session.
/// </summary>
/// <param name="profilePaths">An object containing the profile paths for the session.</param>
/// <param name="initialRunspace">The initial runspace to use for this instance.</param>
/// <param name="ownsInitialRunspace">If true, the PowerShellContext owns this runspace.</param>
public void Initialize(
ProfilePathInfo profilePaths,
Runspace initialRunspace,
bool ownsInitialRunspace)
{
this.Initialize(profilePaths, initialRunspace, ownsInitialRunspace, consoleHost: null);
}

/// <summary>
/// Initializes a new instance of the PowerShellContext class using
/// an existing runspace for the session.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,15 @@ internal class PSReadLinePromptContext : IPromptContext
"..",
"..",
"..",
#if TEST
Copy link
Member Author

Choose a reason for hiding this comment

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

OHH @rjmholt this won't work because we need it defined during test compilation but for this project. Ugh how on earth do we do that?

Copy link
Member Author

Choose a reason for hiding this comment

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

// When using xUnit (dotnet test) the assemblies are deployed to the
// test project folder, invalidating our relative path assumption.
"..",
"..",
"module",
#endif
"PSReadLine");

private static readonly string ReadLineInitScript = $@"
[System.Diagnostics.DebuggerHidden()]
[System.Diagnostics.DebuggerStepThrough()]
param()
end {{
$module = Get-Module -ListAvailable PSReadLine |
Where-Object {{ $_.Version -ge '2.0.2' }} |
Sort-Object -Descending Version |
Select-Object -First 1
if (-not $module) {{
Import-Module '{_psReadLineModulePath.Replace("'", "''")}'
return [Microsoft.PowerShell.PSConsoleReadLine]
}}

Import-Module -ModuleInfo $module
return [Microsoft.PowerShell.PSConsoleReadLine]
}}";

private static readonly Lazy<CmdletInfo> s_lazyInvokeReadLineForEditorServicesCmdletInfo = new Lazy<CmdletInfo>(() =>
{
var type = Type.GetType("Microsoft.PowerShell.EditorServices.Commands.InvokeReadLineForEditorServicesCommand, Microsoft.PowerShell.EditorServices.Hosting");
Expand Down Expand Up @@ -97,14 +86,15 @@ internal static bool TryGetPSReadLineProxy(
using (var pwsh = PowerShell.Create())
{
pwsh.Runspace = runspace;
var psReadLineType = pwsh
.AddScript(ReadLineInitScript, useLocalScope: true)
.Invoke<Type>()
.FirstOrDefault();
pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module")
.AddParameter("Name", _psReadLineModulePath)
.Invoke();

var psReadLineType = Type.GetType("Microsoft.PowerShell.PSConsoleReadLine, Microsoft.PowerShell.PSReadLine2");

if (psReadLineType == null)
{
logger.LogWarning("PSReadLine unable to be loaded: {Reason}", pwsh.HadErrors ? pwsh.Streams.Error[0].ToString() : "<Unknown reason>");
logger.LogWarning("PSConsoleReadline type not found: {Reason}", pwsh.HadErrors ? pwsh.Streams.Error[0].ToString() : "<Unknown reason>");
return false;
}

Expand All @@ -117,7 +107,7 @@ internal static bool TryGetPSReadLineProxy(
// The Type we got back from PowerShell doesn't have the members we expected.
// Could be an older version, a custom build, or something a newer version with
// breaking changes.
logger.LogWarning("PSReadLine unable to be loaded: {Reason}", e);
logger.LogWarning("PSReadLineProxy unable to be initialized: {Reason}", e);
return false;
}
}
Expand Down
28 changes: 16 additions & 12 deletions test/PowerShellEditorServices.Test/PowerShellContextFactory.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.PowerShell.EditorServices.Hosting;
using Microsoft.PowerShell.EditorServices.Services;
using Microsoft.PowerShell.EditorServices.Services.PowerShellContext;
using Microsoft.PowerShell.EditorServices.Test.Shared;
using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.PowerShell.EditorServices.Hosting;
using Microsoft.PowerShell.EditorServices.Services;
using Microsoft.PowerShell.EditorServices.Services.PowerShellContext;
using Microsoft.PowerShell.EditorServices.Test.Shared;

namespace Microsoft.PowerShell.EditorServices.Test
{
Expand All @@ -32,6 +32,8 @@ internal static class PowerShellContextFactory
Path.GetFullPath(
TestUtilities.NormalizePath("../../../../PowerShellEditorServices.Test.Shared/ProfileTest.ps1")));

public static System.Management.Automation.Runspaces.Runspace initialRunspace;

public static PowerShellContextService Create(ILogger logger)
{
PowerShellContextService powerShellContext = new PowerShellContextService(logger, null, isPSReadLineEnabled: false);
Expand All @@ -50,15 +52,17 @@ public static PowerShellContextService Create(ILogger logger)
consoleReplEnabled: false,
usesLegacyReadLine: false);


powerShellContext.Initialize(
TestProfilePaths,
PowerShellContextService.CreateRunspace(
initialRunspace = PowerShellContextService.CreateRunspace(
testHostDetails,
powerShellContext,
new TestPSHostUserInterface(powerShellContext, logger),
logger),
true);
logger);

powerShellContext.Initialize(
TestProfilePaths,
initialRunspace,
ownsInitialRunspace: true,
consoleHost: null);

return powerShellContext;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.PowerShell.EditorServices.Services;
using Microsoft.PowerShell.EditorServices.Services.PowerShellContext;
using Microsoft.PowerShell.EditorServices.Test.Shared;
using Microsoft.PowerShell.EditorServices.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.PowerShell.EditorServices.Services;
using Microsoft.PowerShell.EditorServices.Services.PowerShellContext;
using Microsoft.PowerShell.EditorServices.Test.Shared;
using Microsoft.PowerShell.EditorServices.Utility;
using Xunit;

namespace Microsoft.PowerShell.EditorServices.Test.Console
{
public class PowerShellContextTests : IDisposable
{
// Borrowed from `VersionUtils` which can't be used here due to an initialization problem.
private static bool IsWindows { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

private PowerShellContextService powerShellContext;
private AsyncQueue<SessionStateChangedEventArgs> stateChangeQueue;

Expand Down Expand Up @@ -143,6 +147,17 @@ await this.powerShellContext.ExecuteCommandAsync<string>(
Assert.Equal(expectedString, result.FirstOrDefault(), true);
}

[Trait("Category", "PSReadLine")]
[SkippableFact]
public async Task CanGetPSReadLineProxy()
{
Skip.If(IsWindows, "This test doesn't work on Windows for some reason.");
Copy link
Member Author

Choose a reason for hiding this comment

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

@rjmholt For later debugging 😭

Assert.True(PSReadLinePromptContext.TryGetPSReadLineProxy(
NullLogger.Instance,
PowerShellContextFactory.initialRunspace,
out PSReadLineProxy proxy));
}

#region Helper Methods

private async Task AssertStateChange(PowerShellContextState expectedState)
Expand Down