Skip to content

Commit 6b03c35

Browse files
committed
Merged in Execution Policy bypass move
2 parents ecf1ae2 + b91bb5c commit 6b03c35

File tree

2 files changed

+39
-30
lines changed

2 files changed

+39
-30
lines changed

src/PowerShellEditorServices/Services/PowerShellContext/PowerShellContextService.cs

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ static PowerShellContextService()
7979
{
8080
MethodInfo setterInfo = typeof(Runspace).GetProperty("ApartmentState").GetSetMethod();
8181
Delegate setter = Delegate.CreateDelegate(typeof(Action<Runspace, ApartmentState>), firstArgument: null, method: setterInfo);
82-
s_runspaceApartmentStateSetter = (Action<Runspace, ApartmentState>)setter;
82+
s_runspaceApartmentStateSetter = (Action<Runspace, ApartmentState>) setter;
8383
}
8484

8585
if (VersionUtils.IsPS7OrGreater)
@@ -242,7 +242,7 @@ HostStartupInfo hostStartupInfo
242242
/// <param name="hostUserInterface">The EditorServicesPSHostUserInterface to use for this instance.</param>
243243
/// <param name="logger">An ILogger implementation to use for this instance.</param>
244244
/// <returns></returns>
245-
public static Runspace CreateRunspace(
245+
public static Runspace CreateTestRunspace(
246246
HostStartupInfo hostDetails,
247247
PowerShellContextService powerShellContext,
248248
EditorServicesPSHostUserInterface hostUserInterface,
@@ -262,21 +262,8 @@ public static Runspace CreateRunspace(
262262
/// <param name="psHost">The PSHost that will be used for this Runspace.</param>
263263
/// <param name="languageMode">The language mode inherited from the orginal PowerShell process. This will be used when creating runspaces so that we honor the same language mode.</param>
264264
/// <returns></returns>
265-
public static Runspace CreateRunspace(PSHost psHost, InitialSessionState initialSessionState, List<string> additionalModules = null)
265+
public static Runspace CreateTestRunspace(PSHost psHost, InitialSessionState initialSessionState, List<string> additionalModules = null)
266266
{
267-
if (Environment.GetEnvironmentVariable("PSES_TEST_USE_CREATE_DEFAULT") == "1") {
268-
initialSessionState = InitialSessionState.CreateDefault();
269-
}
270-
271-
// We set the process scope's execution policy (which is really the runspace's scope) to
272-
// Bypass so we can import our bundled modules. This is equivalent in scope to the CLI
273-
// argument `-Bypass`, which (for instance) the extension passes. Thus we emulate this
274-
// behavior for consistency such that unit tests can pass in a similar environment.
275-
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
276-
{
277-
initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass;
278-
}
279-
280267
Runspace runspace = RunspaceFactory.CreateRunspace(psHost, initialSessionState);
281268

282269
// Windows PowerShell must be hosted in STA mode
@@ -534,6 +521,20 @@ bool ownsInitialRunspace
534521
{
535522
this.PromptContext = new LegacyReadLineContext(this);
536523
}
524+
}
525+
526+
/// <summary>
527+
/// Imports the PowerShellEditorServices.Commands module into
528+
/// the runspace. This method will be moved somewhere else soon.
529+
/// </summary>
530+
/// <returns></returns>
531+
public Task ImportCommandsModuleAsync()
532+
{
533+
this.logger.LogTrace($"Importing PowershellEditorServices commands from {s_commandsModulePath}");
534+
535+
PSCommand importCommand = new PSCommand()
536+
.AddCommand("Import-Module")
537+
.AddArgument(s_commandsModulePath);
537538

538539
if (VersionUtils.IsWindows && initialRunspace.InitialSessionState.LanguageMode == PSLanguageMode.FullLanguage)
539540
{
@@ -2262,7 +2263,7 @@ private static string GetStringForPSCommand(PSCommand psCommand)
22622263
return stringBuilder.ToString();
22632264
}
22642265

2265-
private void SetExecutionPolicy()
2266+
internal void RestoreExecutionPolicy()
22662267
{
22672268
this.logger.LogTrace("Setting execution policy...");
22682269

@@ -2288,14 +2289,14 @@ private void SetExecutionPolicy()
22882289
// set to expected values, so we must sift through those.
22892290

22902291
ExecutionPolicy policyToSet = ExecutionPolicy.Bypass;
2291-
var currentUserPolicy = (ExecutionPolicy)policies [policies.Count - 2].Members ["ExecutionPolicy"].Value;
2292+
var currentUserPolicy = (ExecutionPolicy) policies[policies.Count - 2].Members["ExecutionPolicy"].Value;
22922293
if (currentUserPolicy != ExecutionPolicy.Undefined)
22932294
{
22942295
policyToSet = currentUserPolicy;
22952296
}
22962297
else
22972298
{
2298-
var localMachinePolicy = (ExecutionPolicy)policies [policies.Count - 1].Members ["ExecutionPolicy"].Value;
2299+
var localMachinePolicy = (ExecutionPolicy) policies[policies.Count - 1].Members["ExecutionPolicy"].Value;
22992300
if (localMachinePolicy != ExecutionPolicy.Undefined)
23002301
{
23012302
policyToSet = localMachinePolicy;
@@ -2467,7 +2468,7 @@ private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs ar
24672468
case RunspaceState.Closed:
24682469
case RunspaceState.Broken:
24692470
// If the runspace closes or fails, pop the runspace
2470-
((IHostSupportsInteractiveSession)this).PopRunspace();
2471+
((IHostSupportsInteractiveSession) this).PopRunspace();
24712472
break;
24722473
}
24732474
}
@@ -2479,7 +2480,7 @@ private static IEnumerable<string> GetLoadableProfilePaths(ProfilePathInfo profi
24792480
yield break;
24802481
}
24812482

2482-
foreach (string path in new [] { profilePaths.AllUsersAllHosts, profilePaths.AllUsersCurrentHost, profilePaths.CurrentUserAllHosts, profilePaths.CurrentUserCurrentHost })
2483+
foreach (string path in new[] { profilePaths.AllUsersAllHosts, profilePaths.AllUsersCurrentHost, profilePaths.CurrentUserAllHosts, profilePaths.CurrentUserCurrentHost })
24832484
{
24842485
if (path != null && File.Exists(path))
24852486
{
@@ -2511,12 +2512,12 @@ private void StartCommandLoopOnRunspaceAvailable()
25112512
void availabilityChangedHandler(object runspace, RunspaceAvailabilityEventArgs eventArgs)
25122513
{
25132514
if (eventArgs.RunspaceAvailability != RunspaceAvailability.Available ||
2514-
this.versionSpecificOperations.IsDebuggerStopped(this.PromptNest, (Runspace)runspace))
2515+
this.versionSpecificOperations.IsDebuggerStopped(this.PromptNest, (Runspace) runspace))
25152516
{
25162517
return;
25172518
}
25182519

2519-
((Runspace)runspace).AvailabilityChanged -= availabilityChangedHandler;
2520+
((Runspace) runspace).AvailabilityChanged -= availabilityChangedHandler;
25202521
Interlocked.Exchange(ref this.isCommandLoopRestarterSet, 0);
25212522
this.ConsoleReader?.StartCommandLoop();
25222523
}

test/PowerShellEditorServices.Test/PowerShellContextFactory.cs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.IO;
77
using System.Management.Automation;
88
using System.Management.Automation.Runspaces;
9+
using System.Runtime.InteropServices;
910
using System.Threading;
1011
using System.Threading.Tasks;
1112
using Microsoft.Extensions.Logging;
@@ -14,6 +15,7 @@
1415
using Microsoft.PowerShell.EditorServices.Services;
1516
using Microsoft.PowerShell.EditorServices.Services.PowerShellContext;
1617
using Microsoft.PowerShell.EditorServices.Test.Shared;
18+
using Microsoft.PowerShell.EditorServices.Utility;
1719

1820
namespace Microsoft.PowerShell.EditorServices.Test
1921
{
@@ -39,6 +41,16 @@ internal static class PowerShellContextFactory
3941
public static System.Management.Automation.Runspaces.Runspace InitialRunspace;
4042
public static PowerShellContextService Create(ILogger logger, bool isPSReadLineEnabled = false)
4143
{
44+
PowerShellContextService powerShellContext = new PowerShellContextService(logger, null, isPSReadLineEnabled: false);
45+
var initialSessionState = InitialSessionState.CreateDefault();
46+
// We set the process scope's execution policy (which is really the runspace's scope) to
47+
// Bypass so we can import our bundled modules. This is equivalent in scope to the CLI
48+
// argument `-Bypass`, which (for instance) the extension passes. Thus we emulate this
49+
// behavior for consistency such that unit tests can pass in a similar environment.
50+
if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
51+
{
52+
initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass;
53+
}
4254
HostStartupInfo testHostDetails = new HostStartupInfo(
4355
"PowerShell Editor Services Test Host",
4456
"Test.PowerShellEditorServices",
@@ -47,23 +59,19 @@ public static PowerShellContextService Create(ILogger logger, bool isPSReadLineE
4759
TestProfilePaths,
4860
new List<string>(),
4961
new List<string>(),
50-
// TODO: We want to replace this property with an entire initial session state,
51-
// which would then also control the process-scoped execution policy.
52-
InitialSessionState.CreateDefault(),
62+
initialSessionState,
5363
null,
5464
0,
5565
consoleReplEnabled: isPSReadLineEnabled,
5666
usesLegacyReadLine: false,
5767
bundledModulePath: BundledModulePath);
5868

59-
PowerShellContextService powerShellContext = new PowerShellContextService(logger, null, testHostDetails);
60-
61-
InitialRunspace = PowerShellContextService.CreateRunspace(
69+
InitialRunspace = PowerShellContextService.CreateTestRunspace(
6270
testHostDetails,
6371
powerShellContext,
6472
new TestPSHostUserInterface(powerShellContext, logger),
6573
logger);
66-
74+
6775
powerShellContext.Initialize(
6876
testHostDetails,
6977
null,

0 commit comments

Comments
 (0)