From bd4b9711986c6cc6a009ff44881afc176a574ebb Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Wed, 15 Jan 2020 12:42:49 -0800 Subject: [PATCH 1/3] powershell kernel prototype --- .../Protocol/LanguageInfo.cs | 8 + Microsoft.DotNet.Interactive.Jupyter/Shell.cs | 1 + ...osoft.DotNet.Interactive.PowerShell.csproj | 21 ++ .../PowerShellExtensions.cs | 67 ++++ .../PowerShellKernel.cs | 347 ++++++++++++++++++ .../StreamHandler.cs | 180 +++++++++ ...rosoft.DotNet.Interactive.Telemetry.csproj | 2 +- .../CommandLine/CommandLineParser.cs | 4 +- .../kernels/.net-powershell/kernel.json | 12 + dotnet-interactive/dotnet-interactive.csproj | 3 +- 10 files changed, 642 insertions(+), 3 deletions(-) create mode 100644 Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj create mode 100644 Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs create mode 100644 Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs create mode 100644 Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs create mode 100644 dotnet-interactive/ContentFiles/kernels/.net-powershell/kernel.json diff --git a/Microsoft.DotNet.Interactive.Jupyter/Protocol/LanguageInfo.cs b/Microsoft.DotNet.Interactive.Jupyter/Protocol/LanguageInfo.cs index 2bd733eae..0148f36e2 100644 --- a/Microsoft.DotNet.Interactive.Jupyter/Protocol/LanguageInfo.cs +++ b/Microsoft.DotNet.Interactive.Jupyter/Protocol/LanguageInfo.cs @@ -75,6 +75,14 @@ public FSharpLanguageInfo(string version = "4.5") : base("C#", version, "text/x- } } + public class PowerShellLanguageInfo : LanguageInfo + { + public PowerShellLanguageInfo(string version = "7.0") : base("PowerShell", version, "text/x-powershell", ".ps1", pygmentsLexer: "powershell") + { + + } + } + public class VBnetLanguageInfo : LanguageInfo { public VBnetLanguageInfo(string version = "15.0") : base("C#", version, "text/x-vbnet", ".vb", pygmentsLexer: "vbnet") diff --git a/Microsoft.DotNet.Interactive.Jupyter/Shell.cs b/Microsoft.DotNet.Interactive.Jupyter/Shell.cs index 2d257fd5a..773eb0e52 100644 --- a/Microsoft.DotNet.Interactive.Jupyter/Shell.cs +++ b/Microsoft.DotNet.Interactive.Jupyter/Shell.cs @@ -177,6 +177,7 @@ private LanguageInfo GetLanguageInfo(string kernelName) => { "csharp" => new CSharpLanguageInfo(), "fsharp" => new FSharpLanguageInfo(), + "powershell" => new PowerShellLanguageInfo(), _ => null }; } diff --git a/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj b/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj new file mode 100644 index 000000000..a86b48faf --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj @@ -0,0 +1,21 @@ + + + + netcoreapp3.1 + $(NoWarn);2003;CS8002;NU1608; + false + + + + ;NU5104;2003;8002 + + + + + + + + + + + diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs new file mode 100644 index 000000000..d297afefb --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs @@ -0,0 +1,67 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Collections; +using System.Collections.ObjectModel; + +namespace Microsoft.DotNet.Interactive.PowerShell +{ + using System.Management.Automation; + + internal static class PowerShellExtensions + { + public static void InvokeAndClearCommands(this PowerShell pwsh) + { + try + { + pwsh.Invoke(); + } + finally + { + pwsh.Streams.ClearStreams(); + pwsh.Commands.Clear(); + } + } + + public static void InvokeAndClearCommands(this PowerShell pwsh, IEnumerable input) + { + try + { + pwsh.Invoke(input); + } + finally + { + pwsh.Streams.ClearStreams(); + pwsh.Commands.Clear(); + } + } + + public static Collection InvokeAndClearCommands(this PowerShell pwsh) + { + try + { + var result = pwsh.Invoke(); + return result; + } + finally + { + pwsh.Streams.ClearStreams(); + pwsh.Commands.Clear(); + } + } + + public static Collection InvokeAndClearCommands(this PowerShell pwsh, IEnumerable input) + { + try + { + var result = pwsh.Invoke(input); + return result; + } + finally + { + pwsh.Streams.ClearStreams(); + pwsh.Commands.Clear(); + } + } + } +} diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs new file mode 100644 index 000000000..45da9be0d --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -0,0 +1,347 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Language; +using System.Management.Automation.Runspaces; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.DotNet.Interactive.Commands; +using Microsoft.DotNet.Interactive.Events; +using Microsoft.DotNet.Interactive.Formatting; + +namespace Microsoft.DotNet.Interactive.PowerShell +{ + public class PowerShellKernel : KernelBase, IExtensibleKernel + { + internal const string DefaultKernelName = "powershell"; + + private Runspace _runspace; + private SemaphoreSlim _runspaceSemaphore; + private CancellationTokenSource _cancellationSource; + private readonly object _cancellationSourceLock = new object(); + + static PowerShellKernel() + { + Formatter.Register((record, writer) => { + PocketView view = PocketViewTags.pre($"WARN: {record.Message}"); + writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); + }, HtmlFormatter.MimeType); + + Formatter.Register((record, writer) => { + writer.WriteLine($"WARN: {record.Message}"); + }, PlainTextFormatter.MimeType); + + Formatter.Register((record, writer) => { + PocketView view = PocketViewTags.pre($"DEBUG: {record.Message}"); + writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); + }, HtmlFormatter.MimeType); + + Formatter.Register((record, writer) => { + writer.WriteLine($"DEBUG: {record.Message}"); + }, PlainTextFormatter.MimeType); + + Formatter.Register((record, writer) => { + PocketView view = PocketViewTags.pre($"VERBOSE: {record.Message}"); + writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); + }, HtmlFormatter.MimeType); + + Formatter.Register((record, writer) => { + writer.WriteLine($"VERBOSE: {record.Message}"); + }, PlainTextFormatter.MimeType); + } + + public PowerShellKernel() + { + _runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault()); + _runspace.Open(); + _runspaceSemaphore = new SemaphoreSlim(1, 1); + _cancellationSource = new CancellationTokenSource(); + Name = DefaultKernelName; + } + + #region Overrides + + protected override Task HandleAsync( + IKernelCommand command, + KernelInvocationContext context) + { + if (command is KernelCommandBase kb) + { + if (kb.Handler == null) + { + switch (command) + { + case SubmitCode submitCode: + submitCode.Handler = async (_, invocationContext) => + { + await HandleSubmitCode(submitCode, context); + }; + break; + + case RequestCompletion requestCompletion: + requestCompletion.Handler = async (_, invocationContext) => + { + await HandleRequestCompletion(requestCompletion, invocationContext); + }; + break; + + case CancelCurrentCommand interruptExecution: + interruptExecution.Handler = async (_, invocationContext) => + { + await HandleCancelCurrentCommand(interruptExecution, invocationContext); + }; + break; + } + } + } + + return Task.CompletedTask; + } + + #endregion + + #region Handlers + + private async Task HandleSubmitCode( + SubmitCode submitCode, + KernelInvocationContext context) + { + CancellationTokenSource cancellationSource; + lock (_cancellationSourceLock) + { + cancellationSource = _cancellationSource; + } + + var codeSubmissionReceived = new CodeSubmissionReceived(submitCode); + + context.Publish(codeSubmissionReceived); + + var code = submitCode.Code; + if (IsCompleteSubmission(code)) + { + context.Publish(new CompleteCodeSubmissionReceived(submitCode)); + } + else + { + context.Publish(new IncompleteCodeSubmissionReceived(submitCode)); + } + + if (submitCode.SubmissionType == SubmissionType.Diagnose) + { + return; + } + + Exception exception = null; + Collection results = null; + if (!cancellationSource.IsCancellationRequested) + { + await _runspaceSemaphore.WaitAsync(); + try + { + using(var ps = System.Management.Automation.PowerShell.Create(_runspace)) + { + RegisterPowerShellStreams(ps, context, submitCode); + try + { + results = ps + .AddScript(code) + .AddCommand("Out-String") + .InvokeAndClearCommands(); + } + catch (Exception e) + { + results = ps + .AddCommand("Out-String") + .AddParameter("InputObject", new ErrorRecord(e, null, ErrorCategory.NotSpecified, null)) + .InvokeAndClearCommands(); + } + } + } + catch (Exception e) + { + exception = e; + } + finally + { + _runspaceSemaphore.Release(); + } + } + + if (!cancellationSource.IsCancellationRequested) + { + if (exception != null) + { + string message = null; + context.Publish(new CommandFailed(exception, submitCode, message)); + } + else + { + if (results != null) + { + + var formattedValues = FormattedValue.FromObject(results.Single()); + context.Publish( + new ReturnValueProduced( + results, + submitCode, + formattedValues)); + } + } + } + else + { + context.Publish(new CommandFailed(null, submitCode, "Command cancelled")); + } + } + + private async Task HandleRequestCompletion( + RequestCompletion requestCompletion, + KernelInvocationContext context) + { + var completionRequestReceived = new CompletionRequestReceived(requestCompletion); + + context.Publish(completionRequestReceived); + + var completionList = + await GetCompletionList( + requestCompletion.Code, + requestCompletion.CursorPosition); + + context.Publish(new CompletionRequestCompleted(completionList, requestCompletion)); + } + + private Task HandleCancelCurrentCommand( + CancelCurrentCommand cancelCurrentCommand, + KernelInvocationContext context) + { + var reply = new CurrentCommandCancelled(cancelCurrentCommand); + lock (_cancellationSourceLock) + { + _cancellationSource.Cancel(); + _cancellationSource = new CancellationTokenSource(); + } + + context.Publish(reply); + + return Task.CompletedTask; + } + + #endregion + + public bool IsCompleteSubmission(string code) + { + Parser.ParseInput(code, out Token[] tokens, out ParseError[] errors); + return errors.Length > 0; + } + + private void PublishOutput( + string output, + KernelInvocationContext context, + IKernelCommand command) + { + var formattedValues = new List + { + new FormattedValue( + PlainTextFormatter.MimeType, output) + }; + + context.Publish( + new StandardOutputValueProduced( + output, + command, + formattedValues)); + } + + private void PublishStreamRecord( + object output, + KernelInvocationContext context, + IKernelCommand command) + { + context.Publish( + new DisplayedValueProduced( + output, + command, + FormattedValue.FromObject(output))); + } + + private void PublishError( + string error, + KernelInvocationContext context, + IKernelCommand command) + { + var formattedValues = new List + { + new FormattedValue( + PlainTextFormatter.MimeType, error) + }; + + context.Publish( + new StandardErrorValueProduced( + error, + command, + formattedValues)); + } + + private async Task> GetCompletionList( + string code, + int cursorPosition) + { + await _runspaceSemaphore.WaitAsync(); + + try + { + using (var ps = System.Management.Automation.PowerShell.Create(_runspace)) + { + CommandCompletion completion = CommandCompletion.CompleteInput(code, cursorPosition, null, ps); + + return completion.CompletionMatches.Select(c => new CompletionItem( + displayText: c.CompletionText, + kind: c.ResultType.ToString(), + documentation: c.ToolTip + )); + } + } + finally + { + _runspaceSemaphore.Release(); + } + } + + public async Task LoadExtensionsFromDirectory( + DirectoryInfo directory, + KernelInvocationContext context) + { + var extensionsDirectory = + new DirectoryInfo( + Path.Combine( + directory.FullName, + "interactive-extensions", + "dotnet", + "cs")); + + await new KernelExtensionAssemblyLoader().LoadFromAssembliesInDirectory( + extensionsDirectory, + context.HandlingKernel, + context); + } + + private void RegisterPowerShellStreams( + System.Management.Automation.PowerShell powerShell, + KernelInvocationContext context, + IKernelCommand command) + { + var streamHandler = new StreamHandler(context, command); + powerShell.Streams.Debug.DataAdding += streamHandler.DebugDataAdding; + powerShell.Streams.Warning.DataAdding += streamHandler.WarningDataAdding; + powerShell.Streams.Error.DataAdding += streamHandler.ErrorDataAdding; + powerShell.Streams.Verbose.DataAdding += streamHandler.VerboseDataAdding; + powerShell.Streams.Information.DataAdding += streamHandler.InformationDataAdding; + } + } +} diff --git a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs new file mode 100644 index 000000000..a607583a8 --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs @@ -0,0 +1,180 @@ +// Copyright (c) .NET Foundation and contributors. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +using System.Linq; +using Microsoft.DotNet.Interactive.Commands; +using Microsoft.DotNet.Interactive.Events; +using Microsoft.DotNet.Interactive.Formatting; + +namespace Microsoft.DotNet.Interactive.PowerShell +{ + using System.Management.Automation; + + internal class StreamHandler + { + private static readonly PowerShell s_powerShell = PowerShell.Create(); + private static readonly object s_powerShellLock = new object(); + KernelInvocationContext _context; + IKernelCommand _command; + + static StreamHandler() + { + SetupRecordFormatters(); + } + + public StreamHandler(KernelInvocationContext context, IKernelCommand command) + { + _context = context; + _command = command; + } + + public void DebugDataAdding(object sender, DataAddingEventArgs e) + { + if(e.ItemAdded is DebugRecord record) + { + PublishStreamRecord(record, _context, _command); + } + } + + public void ErrorDataAdding(object sender, DataAddingEventArgs e) + { + if(e.ItemAdded is ErrorRecord record) + { + PublishStreamRecord(record, _context, _command); + } + } + + public void InformationDataAdding(object sender, DataAddingEventArgs e) + { + if(e.ItemAdded is InformationRecord record) + { + PublishStreamRecord(record, _context, _command); + } + } + + public void ProgressDataAdding(object sender, DataAddingEventArgs e) + { + if(e.ItemAdded is ProgressRecord record) + { + PublishStreamRecord(record, _context, _command); + } + } + + public void VerboseDataAdding(object sender, DataAddingEventArgs e) + { + if(e.ItemAdded is VerboseRecord record) + { + PublishStreamRecord(record, _context, _command); + } + } + + public void WarningDataAdding(object sender, DataAddingEventArgs e) + { + if(e.ItemAdded is WarningRecord record) + { + PublishStreamRecord(record, _context, _command); + } + } + + private void PublishStreamRecord( + object output, + KernelInvocationContext context, + IKernelCommand command) + { + context.Publish( + new DisplayedValueProduced( + output, + command, + FormattedValue.FromObject(output))); + } + + private static void SetupRecordFormatters() + { + // DebugRecord + Formatter.Register((record, writer) => { + PocketView view = PocketViewTags.pre($"DEBUG: {record.Message}"); + writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); + }, HtmlFormatter.MimeType); + + Formatter.Register((record, writer) => { + writer.WriteLine($"DEBUG: {record.Message}"); + }, PlainTextFormatter.MimeType); + + // ErrorRecord + Formatter.Register((record, writer) => { + string result = null; + lock(s_powerShellLock) + { + var errorDetails = s_powerShell.AddCommand("Microsoft.PowerShell.Utility\\Out-String") + .AddParameter("InputObject", record) + .InvokeAndClearCommands(); + result = errorDetails.Single(); + } + + if (result != null) + { + PocketView view = PocketViewTags.pre(result); + writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); + } + }, HtmlFormatter.MimeType); + + Formatter.Register((record, writer) => { + string result = null; + lock(s_powerShellLock) + { + var errorDetails = s_powerShell.AddCommand("Microsoft.PowerShell.Utility\\Out-String") + .AddParameter("InputObject", record) + .InvokeAndClearCommands(); + result = errorDetails.Single(); + } + + if (result != null) + { + writer.WriteLine(result); + } + }, PlainTextFormatter.MimeType); + + // InformationRecord + Formatter.Register((record, writer) => { + string prefix = (record.Tags.Count == 1 && record.Tags[0] == "__PipelineObject__") ? "OUTPUT:" : "INFORMATION:"; + PocketView view = PocketViewTags.pre($"{prefix} {record.MessageData}"); + writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); + }, HtmlFormatter.MimeType); + + Formatter.Register((record, writer) => { + string prefix = (record.Tags.Count == 1 && record.Tags[0] == "__PipelineObject__") ? "OUTPUT:" : "INFORMATION:"; + writer.WriteLine($"{prefix} {record.MessageData}"); + }, PlainTextFormatter.MimeType); + + // ProgressRecord + Formatter.Register((record, writer) => { + PocketView view = PocketViewTags.pre($"PROGRESS: {record.StatusDescription}"); + writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); + }, HtmlFormatter.MimeType); + + Formatter.Register((record, writer) => { + writer.WriteLine($"PROGRESS: {record.StatusDescription}"); + }, PlainTextFormatter.MimeType); + + // VerboseRecord + Formatter.Register((record, writer) => { + PocketView view = PocketViewTags.pre($"VERBOSE: {record.Message}"); + writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); + }, HtmlFormatter.MimeType); + + Formatter.Register((record, writer) => { + writer.WriteLine($"VERBOSE: {record.Message}"); + }, PlainTextFormatter.MimeType); + + // WarningRecord + Formatter.Register((record, writer) => { + PocketView view = PocketViewTags.pre($"WARNING: {record.Message}"); + writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); + }, HtmlFormatter.MimeType); + + Formatter.Register((record, writer) => { + writer.WriteLine($"WARNING: {record.Message}"); + }, PlainTextFormatter.MimeType); + } + } +} diff --git a/Microsoft.DotNet.Interactive.Telemetry/Microsoft.DotNet.Interactive.Telemetry.csproj b/Microsoft.DotNet.Interactive.Telemetry/Microsoft.DotNet.Interactive.Telemetry.csproj index c074e6011..96c84cd45 100644 --- a/Microsoft.DotNet.Interactive.Telemetry/Microsoft.DotNet.Interactive.Telemetry.csproj +++ b/Microsoft.DotNet.Interactive.Telemetry/Microsoft.DotNet.Interactive.Telemetry.csproj @@ -6,7 +6,7 @@ - + diff --git a/dotnet-interactive/CommandLine/CommandLineParser.cs b/dotnet-interactive/CommandLine/CommandLineParser.cs index 1ce626b5e..b5ca08982 100644 --- a/dotnet-interactive/CommandLine/CommandLineParser.cs +++ b/dotnet-interactive/CommandLine/CommandLineParser.cs @@ -15,6 +15,7 @@ using Microsoft.DotNet.Interactive.CSharp; using Microsoft.DotNet.Interactive.FSharp; using Microsoft.DotNet.Interactive.Jupyter; +using Microsoft.DotNet.Interactive.PowerShell; using Microsoft.DotNet.Interactive.Server; using Microsoft.DotNet.Interactive.Telemetry; using Microsoft.Extensions.DependencyInjection; @@ -218,7 +219,8 @@ private static IKernel CreateKernel(string defaultKernelName) .UseWho() .UseDefaultNamespaces() .UseXplot() - .UseMathAndLaTeX() + .UseMathAndLaTeX(), + new PowerShellKernel() } .UseDefaultMagicCommands() .UseAbout(); diff --git a/dotnet-interactive/ContentFiles/kernels/.net-powershell/kernel.json b/dotnet-interactive/ContentFiles/kernels/.net-powershell/kernel.json new file mode 100644 index 000000000..dc5a10f95 --- /dev/null +++ b/dotnet-interactive/ContentFiles/kernels/.net-powershell/kernel.json @@ -0,0 +1,12 @@ +{ + "argv": [ + "dotnet", + "interactive", + "jupyter", + "--default-kernel", + "powershell", + "{connection_file}" + ], + "display_name": ".NET (PowerShell)", + "language": "PowerShell" +} diff --git a/dotnet-interactive/dotnet-interactive.csproj b/dotnet-interactive/dotnet-interactive.csproj index 2016caf1b..f9bb13d97 100644 --- a/dotnet-interactive/dotnet-interactive.csproj +++ b/dotnet-interactive/dotnet-interactive.csproj @@ -64,7 +64,7 @@ all runtime; build; native; contentfiles; analyzers - + @@ -75,6 +75,7 @@ + From ca9584007e47da27dced470a4b5a6c3d83f45dcf Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Thu, 23 Jan 2020 12:18:02 -0800 Subject: [PATCH 2/3] order matters --- .../Commands/CommandUtils.cs | 19 +++ .../Commands/TracePipelineObjectCommand.cs | 69 +++++++++ ...osoft.DotNet.Interactive.PowerShell.csproj | 6 + ...crosoft.DotNet.Interactive.PowerShell.psd1 | 131 ++++++++++++++++++ .../PowerShellKernel.cs | 68 +++------ .../StreamHandler.cs | 6 +- 6 files changed, 244 insertions(+), 55 deletions(-) create mode 100644 Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs create mode 100644 Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs create mode 100644 Microsoft.DotNet.Interactive.PowerShell/Modules/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.psd1 diff --git a/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs b/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs new file mode 100644 index 000000000..883f7927c --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs @@ -0,0 +1,19 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using System.Management.Automation; +using Microsoft.PowerShell.Commands; + +namespace Microsoft.DotNet.Interactive.PowerShell.Commands +{ + internal class CommandUtils + { + internal readonly static CmdletInfo OutStringCmdletInfo = new CmdletInfo("Out-String", typeof(OutStringCommand)); + internal readonly static CmdletInfo WriteInformationCmdletInfo = new CmdletInfo("Write-Information", typeof(WriteInformationCommand)); + + internal readonly static object BoxedTrue = (object)true; + internal readonly static object BoxedFalse = (object)false; + } +} diff --git a/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs new file mode 100644 index 000000000..beb5d8dc1 --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs @@ -0,0 +1,69 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using System; +using System.Collections; +using System.Collections.Generic; +using Microsoft.PowerShell.Commands; + +namespace Microsoft.DotNet.Interactive.PowerShell.Commands +{ + using System.Management.Automation; + + /// + /// Writes the formatted output of the pipeline object to the information stream before passing the object down to the pipeline. + /// + /// + /// This Cmdlet behaves like 'Tee-Object'. + /// An input pipeline object is first pushed through a steppable pipeline that consists of 'Out-String | Write-Information -Tags "__PipelineObject__"', + /// and then it's written out back to the pipeline without change. In this approach, we can intercept and trace the pipeline objects in a streaming way + /// and keep the objects in pipeline at the same time. + /// + [Cmdlet(VerbsDiagnostic.Trace, "PipelineObject")] + public sealed class TracePipelineObjectCommand : PSCmdlet + { + /// + /// The object from pipeline. + /// + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] + public object InputObject { get; set; } + + private static PowerShell s_pwsh; + private SteppablePipeline _stepPipeline; + + static TracePipelineObjectCommand() + { + s_pwsh = PowerShell.Create(); + s_pwsh.AddCommand(CommandUtils.OutStringCmdletInfo).AddParameter("Stream", CommandUtils.BoxedTrue) + .AddCommand(CommandUtils.WriteInformationCmdletInfo).AddParameter("Tags", "__PipelineObject__"); + } + + /// + /// BeginProcessing override. + /// + protected override void BeginProcessing() + { + _stepPipeline = s_pwsh.GetSteppablePipeline(); + _stepPipeline.Begin(this); + } + + /// + /// ProcessRecord override. + /// + protected override void ProcessRecord() + { + _stepPipeline.Process(InputObject); + WriteObject(InputObject); + } + + /// + /// EndProcessing override. + /// + protected override void EndProcessing() + { + _stepPipeline.End(); + } + } +} diff --git a/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj b/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj index a86b48faf..f5bf09479 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj +++ b/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj @@ -18,4 +18,10 @@ + + + Modules\%(RecursiveDir)\%(FileName)%(Extension) + PreserveNewest + + diff --git a/Microsoft.DotNet.Interactive.PowerShell/Modules/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.psd1 b/Microsoft.DotNet.Interactive.PowerShell/Modules/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.psd1 new file mode 100644 index 000000000..e18c8338b --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/Modules/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.psd1 @@ -0,0 +1,131 @@ +# +# Module manifest for module 'Microsoft.DotNet.Interactive.PowerShell' +# +# Generated by: tyleonha +# +# Generated on: 1/23/2020 +# + +@{ + +# Script module or binary module file associated with this manifest. +# RootModule = '' + +# Version number of this module. +ModuleVersion = '0.0.1' + +# Supported PSEditions +# CompatiblePSEditions = @() + +# ID used to uniquely identify this module +GUID = 'c3ca4cca-fd49-4b1e-a79e-b12afb026068' + +# Author of this module +Author = 'Microsoft Corporation' + +# Company or vendor of this module +CompanyName = 'Microsoft Corporation' + +# Copyright statement for this module +Copyright = '(c) Microsoft Corporation. All rights reserved.' + +# Description of the functionality provided by this module +# Description = '' + +# Minimum version of the PowerShell engine required by this module +# PowerShellVersion = '' + +# Name of the PowerShell host required by this module +# PowerShellHostName = '' + +# Minimum version of the PowerShell host required by this module +# PowerShellHostVersion = '' + +# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# DotNetFrameworkVersion = '' + +# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. +# CLRVersion = '' + +# Processor architecture (None, X86, Amd64) required by this module +# ProcessorArchitecture = '' + +# Modules that must be imported into the global environment prior to importing this module +# RequiredModules = @() + +# Assemblies that must be loaded prior to importing this module +# RequiredAssemblies = @() + +# Script files (.ps1) that are run in the caller's environment prior to importing this module. +# ScriptsToProcess = @() + +# Type files (.ps1xml) to be loaded when importing this module +# TypesToProcess = @() + +# Format files (.ps1xml) to be loaded when importing this module +# FormatsToProcess = @() + +# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess +NestedModules = @('Microsoft.DotNet.Interactive.PowerShell.dll') + +# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. +FunctionsToExport = @() + +# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. +CmdletsToExport = @('Trace-PipelineObject') + +# Variables to export from this module +VariablesToExport = '*' + +# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. +AliasesToExport = @() + +# DSC resources to export from this module +# DscResourcesToExport = @() + +# List of all modules packaged with this module +# ModuleList = @() + +# List of all files packaged with this module +# FileList = @() + +# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. +PrivateData = @{ + + PSData = @{ + + # Tags applied to this module. These help with module discovery in online galleries. + # Tags = @() + + # A URL to the license for this module. + # LicenseUri = '' + + # A URL to the main website for this project. + # ProjectUri = '' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + # ReleaseNotes = '' + + # Prerelease string of this module + # Prerelease = '' + + # Flag to indicate whether the module requires explicit user acceptance for install/update/save + # RequireLicenseAcceptance = $false + + # External dependent modules of this module + # ExternalModuleDependencies = @() + + } # End of PSData hashtable + +} # End of PrivateData hashtable + +# HelpInfo URI of this module +# HelpInfoURI = '' + +# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. +# DefaultCommandPrefix = '' + +} diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index 45da9be0d..779b1f5fd 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -9,6 +9,7 @@ using System.Management.Automation; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.DotNet.Interactive.Commands; @@ -26,43 +27,19 @@ public class PowerShellKernel : KernelBase, IExtensibleKernel private CancellationTokenSource _cancellationSource; private readonly object _cancellationSourceLock = new object(); - static PowerShellKernel() - { - Formatter.Register((record, writer) => { - PocketView view = PocketViewTags.pre($"WARN: {record.Message}"); - writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); - }, HtmlFormatter.MimeType); - - Formatter.Register((record, writer) => { - writer.WriteLine($"WARN: {record.Message}"); - }, PlainTextFormatter.MimeType); - - Formatter.Register((record, writer) => { - PocketView view = PocketViewTags.pre($"DEBUG: {record.Message}"); - writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); - }, HtmlFormatter.MimeType); - - Formatter.Register((record, writer) => { - writer.WriteLine($"DEBUG: {record.Message}"); - }, PlainTextFormatter.MimeType); - - Formatter.Register((record, writer) => { - PocketView view = PocketViewTags.pre($"VERBOSE: {record.Message}"); - writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); - }, HtmlFormatter.MimeType); - - Formatter.Register((record, writer) => { - writer.WriteLine($"VERBOSE: {record.Message}"); - }, PlainTextFormatter.MimeType); - } - public PowerShellKernel() { - _runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault()); + var iss = InitialSessionState.CreateDefault(); + _runspace = RunspaceFactory.CreateRunspace(iss); _runspace.Open(); _runspaceSemaphore = new SemaphoreSlim(1, 1); _cancellationSource = new CancellationTokenSource(); Name = DefaultKernelName; + + string psModulePath = Environment.GetEnvironmentVariable("PSModulePath"); + Environment.SetEnvironmentVariable("PSModulePath", + psModulePath + Path.PathSeparator + + System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/Modules"); } #region Overrides @@ -138,7 +115,6 @@ private async Task HandleSubmitCode( } Exception exception = null; - Collection results = null; if (!cancellationSource.IsCancellationRequested) { await _runspaceSemaphore.WaitAsync(); @@ -149,17 +125,18 @@ private async Task HandleSubmitCode( RegisterPowerShellStreams(ps, context, submitCode); try { - results = ps - .AddScript(code) - .AddCommand("Out-String") - .InvokeAndClearCommands(); + ps.AddScript(code) + .AddCommand(@"Microsoft.DotNet.Interactive.PowerShell\Trace-PipelineObject") + .InvokeAndClearCommands(); } catch (Exception e) { - results = ps - .AddCommand("Out-String") + string stringifiedErrorRecord = + ps.AddCommand(@"Out-String") .AddParameter("InputObject", new ErrorRecord(e, null, ErrorCategory.NotSpecified, null)) - .InvokeAndClearCommands(); + .InvokeAndClearCommands()[0]; + + StreamHandler.PublishStreamRecord(stringifiedErrorRecord, context, submitCode); } } } @@ -180,19 +157,6 @@ private async Task HandleSubmitCode( string message = null; context.Publish(new CommandFailed(exception, submitCode, message)); } - else - { - if (results != null) - { - - var formattedValues = FormattedValue.FromObject(results.Single()); - context.Publish( - new ReturnValueProduced( - results, - submitCode, - formattedValues)); - } - } } else { diff --git a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs index a607583a8..8a70b82ad 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs @@ -76,7 +76,7 @@ public void WarningDataAdding(object sender, DataAddingEventArgs e) } } - private void PublishStreamRecord( + internal static void PublishStreamRecord( object output, KernelInvocationContext context, IKernelCommand command) @@ -136,13 +136,13 @@ private static void SetupRecordFormatters() // InformationRecord Formatter.Register((record, writer) => { - string prefix = (record.Tags.Count == 1 && record.Tags[0] == "__PipelineObject__") ? "OUTPUT:" : "INFORMATION:"; + string prefix = (record.Tags.Count == 1 && record.Tags[0] == "__PipelineObject__") ? "" : "INFORMATION:"; PocketView view = PocketViewTags.pre($"{prefix} {record.MessageData}"); writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); }, HtmlFormatter.MimeType); Formatter.Register((record, writer) => { - string prefix = (record.Tags.Count == 1 && record.Tags[0] == "__PipelineObject__") ? "OUTPUT:" : "INFORMATION:"; + string prefix = (record.Tags.Count == 1 && record.Tags[0] == "__PipelineObject__") ? "" : "INFORMATION:"; writer.WriteLine($"{prefix} {record.MessageData}"); }, PlainTextFormatter.MimeType); From 70a4e13b4aa51935aa961fe0f23eb76bcb3ae52c Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Thu, 23 Jan 2020 13:31:14 -0800 Subject: [PATCH 3/3] readd to sln --- dotnet-interactive.sln | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/dotnet-interactive.sln b/dotnet-interactive.sln index 6d05c8696..7423469d9 100644 --- a/dotnet-interactive.sln +++ b/dotnet-interactive.sln @@ -39,6 +39,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XPlot.DotNet.Interactive.Ke EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dotnet-interactive.Profiler", "dotnet-interactive.Profiler\dotnet-interactive.Profiler.csproj", "{71098504-D54D-4F2B-AF1F-FD54C471067B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.DotNet.Interactive.PowerShell", "Microsoft.DotNet.Interactive.PowerShell\Microsoft.DotNet.Interactive.PowerShell.csproj", "{CE412E28-8660-43CA-8E0B-293EAC624623}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -241,6 +243,18 @@ Global {71098504-D54D-4F2B-AF1F-FD54C471067B}.Release|x64.Build.0 = Release|Any CPU {71098504-D54D-4F2B-AF1F-FD54C471067B}.Release|x86.ActiveCfg = Release|Any CPU {71098504-D54D-4F2B-AF1F-FD54C471067B}.Release|x86.Build.0 = Release|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Debug|x64.ActiveCfg = Debug|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Debug|x64.Build.0 = Debug|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Debug|x86.ActiveCfg = Debug|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Debug|x86.Build.0 = Debug|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Release|Any CPU.Build.0 = Release|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Release|x64.ActiveCfg = Release|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Release|x64.Build.0 = Release|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Release|x86.ActiveCfg = Release|Any CPU + {CE412E28-8660-43CA-8E0B-293EAC624623}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE