|
| 1 | +// |
| 2 | +// Copyright (c) Microsoft. All rights reserved. |
| 3 | +// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| 4 | +// |
| 5 | + |
| 6 | +using System; |
| 7 | +using System.Management.Automation; |
| 8 | +using System.Management.Automation.Runspaces; |
| 9 | +using System.Reflection; |
| 10 | +using System.Threading; |
| 11 | + |
| 12 | +namespace Microsoft.PowerShell.EditorServices.Commands |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// The Start-EditorServices command, the conventional entrypoint for PowerShell Editor Services. |
| 16 | + /// </summary> |
| 17 | + [Cmdlet("__Invoke", "ReadLineForEditorServices")] |
| 18 | + public sealed class InvokeReadLineForEditorServicesCommand : PSCmdlet |
| 19 | + { |
| 20 | + private delegate string ReadLineInvoker( |
| 21 | + Runspace runspace, |
| 22 | + EngineIntrinsics engineIntrinsics, |
| 23 | + CancellationToken cancellationToken); |
| 24 | + |
| 25 | + private static Lazy<ReadLineInvoker> s_readLine = new Lazy<ReadLineInvoker>(() => |
| 26 | + { |
| 27 | + Type type = Type.GetType("Microsoft.PowerShell.PSConsoleReadLine, Microsoft.PowerShell.PSReadLine2"); |
| 28 | + MethodInfo method = type?.GetMethod( |
| 29 | + "ReadLine", |
| 30 | + new[] { typeof(Runspace), typeof(EngineIntrinsics), typeof(CancellationToken) }); |
| 31 | + |
| 32 | + // TODO: Handle method being null here. This shouldn't ever happen. |
| 33 | + |
| 34 | + return (ReadLineInvoker)method.CreateDelegate(typeof(ReadLineInvoker)); |
| 35 | + }); |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// The ID to give to the host's profile. |
| 39 | + /// </summary> |
| 40 | + [Parameter(Mandatory = true)] |
| 41 | + [ValidateNotNullOrEmpty] |
| 42 | + public CancellationToken CancellationToken { get; set; } |
| 43 | + |
| 44 | + protected override void EndProcessing() |
| 45 | + { |
| 46 | + // This returns a string. |
| 47 | + object result = s_readLine.Value( |
| 48 | + Runspace.DefaultRunspace, |
| 49 | + SessionState.PSVariable.Get("ExecutionContext").Value as EngineIntrinsics, |
| 50 | + CancellationToken |
| 51 | + ); |
| 52 | + |
| 53 | + WriteObject(result); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments