diff --git a/Microsoft.DotNet.Interactive.Jupyter/Protocol/LanguageInfo.cs b/Microsoft.DotNet.Interactive.Jupyter/Protocol/LanguageInfo.cs index 2bd733eaea..0148f36e20 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 2d257fd5a9..773eb0e52f 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.Tests/Microsoft.DotNet.Interactive.PowerShell.Tests.csproj b/Microsoft.DotNet.Interactive.PowerShell.Tests/Microsoft.DotNet.Interactive.PowerShell.Tests.csproj new file mode 100644 index 0000000000..2f94dd0760 --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell.Tests/Microsoft.DotNet.Interactive.PowerShell.Tests.csproj @@ -0,0 +1,20 @@ + + + + netcoreapp3.1 + latest + false + + + + + + + + + + + + + + diff --git a/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs b/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs new file mode 100644 index 0000000000..67eceb99b0 --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs @@ -0,0 +1,17 @@ +// 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.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 0000000000..98831c156b --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs @@ -0,0 +1,63 @@ +// 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. + +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)] + [AllowNull] + public object InputObject { get; set; } + + private static PowerShell _pwsh; + private SteppablePipeline _stepPipeline; + + static TracePipelineObjectCommand() + { + _pwsh = PowerShell.Create(); + _pwsh.AddCommand(CommandUtils.OutStringCmdletInfo).AddParameter("Stream", CommandUtils.BoxedTrue) + .AddCommand(CommandUtils.WriteInformationCmdletInfo).AddParameter("Tags", "__PipelineObject__"); + } + + /// + /// BeginProcessing override. + /// + protected override void BeginProcessing() + { + _stepPipeline = _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 new file mode 100644 index 0000000000..47fcc1170a --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj @@ -0,0 +1,28 @@ + + + + netcoreapp3.1 + latest + $(NoWarn);2003;CS8002;NU1608; + false + + + + ;NU5104;2003;8002 + + + + + + + + + + + + + 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 0000000000..c6bdb22ff0 --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/Modules/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.psd1 @@ -0,0 +1,94 @@ +# 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. + +@{ +# Version number of this module. +ModuleVersion = '0.1.0' + +# Supported PSEditions +CompatiblePSEditions = @('Core') + +# 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 = 'Copyright (c) .NET Foundation and contributors. All rights reserved.' + +# Description of the functionality provided by this module +# Description = '' + +# Minimum version of the PowerShell engine required by this module +PowerShellVersion = '7.0.0' + +# 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 = @() + +# 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 = @('Microsoft', '.NET', 'Jupyter', 'dotnet') + + # A URL to the license for this module. + LicenseUri = 'https://github.com/dotnet/interactive/blob/master/License.txt' + + # A URL to the main website for this project. + ProjectUri = 'https://github.com/dotnet/interactive' + + # A URL to an icon representing this module. + # IconUri = '' + + # ReleaseNotes of this module + ReleaseNotes = '# v0.1.0 + +Initial release. +' + + # Prerelease string of this module + # Prerelease = '' + } # 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/PowerShellExtensions.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs new file mode 100644 index 0000000000..0ad4b89040 --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs @@ -0,0 +1,81 @@ +// 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; +using System.Threading.Tasks; + +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 async Task InvokeAndClearCommandsAsync(this PowerShell pwsh) + { + try + { + await pwsh.InvokeAsync().ConfigureAwait(false); + } + 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 0000000000..136f93e603 --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -0,0 +1,253 @@ +// 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.IO; +using System.Linq; +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.PowerShell.Commands; + +namespace Microsoft.DotNet.Interactive.PowerShell +{ + using System.Management.Automation; + + public class PowerShellKernel : KernelBase + { + internal const string DefaultKernelName = "powershell"; + + private readonly object _cancellationSourceLock = new object(); + private Runspace _runspace; + private PowerShell _pwsh; + private CancellationTokenSource _cancellationSource; + + public PowerShellKernel() + { + //Sets the distribution channel to "PSES" so starts can be distinguished in PS7+ telemetry + Environment.SetEnvironmentVariable("POWERSHELL_DISTRIBUTION_CHANNEL", "dotnet-interactive-powershell"); + + _runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault()); + _runspace.Open(); + _pwsh = PowerShell.Create(_runspace); + _cancellationSource = new CancellationTokenSource(); + Name = DefaultKernelName; + + // Add Modules directory that contains the helper modules + string psModulePath = Environment.GetEnvironmentVariable("PSModulePath"); + + Environment.SetEnvironmentVariable("PSModulePath", + psModulePath + Path.PathSeparator + Path.Join( + Path.GetDirectoryName(typeof(PowerShellKernel).Assembly.Location), + "Modules")); + } + + #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 = (_, invocationContext) => + { + HandleSubmitCode(submitCode, context); + return Task.CompletedTask; + }; + break; + + case RequestCompletion requestCompletion: + requestCompletion.Handler = (_, invocationContext) => + { + HandleRequestCompletion(requestCompletion, invocationContext); + return Task.CompletedTask; + }; + break; + + case CancelCurrentCommand interruptExecution: + interruptExecution.Handler = (_, invocationContext) => + { + HandleCancelCurrentCommand(interruptExecution, invocationContext); + return Task.CompletedTask; + }; + break; + } + } + } + + return Task.CompletedTask; + } + + #endregion + + #region Handlers + + private void HandleSubmitCode( + SubmitCode submitCode, + KernelInvocationContext context) + { + CancellationTokenSource cancellationSource; + lock (_cancellationSourceLock) + { + cancellationSource = _cancellationSource; + } + + // Acknowledge that we received the request. + var codeSubmissionReceived = new CodeSubmissionReceived(submitCode); + context.Publish(codeSubmissionReceived); + + // Test is the code we got is actually able to run. + var code = submitCode.Code; + if (IsCompleteSubmission(code, out ParseError[] parseErrors)) + { + context.Publish(new CompleteCodeSubmissionReceived(submitCode)); + } + else + { + context.Publish(new IncompleteCodeSubmissionReceived(submitCode)); + } + + // If there were parse errors, publish them and return early. + if (parseErrors.Length > 0) + { + context.Fail(message: string.Join(Environment.NewLine + Environment.NewLine, + parseErrors.Select(pe => pe.ToString()))); + return; + } + + // Do nothing if we get a Diagnose type. + if (submitCode.SubmissionType == SubmissionType.Diagnose) + { + return; + } + + if (cancellationSource.IsCancellationRequested) + { + context.Fail(null, "Command cancelled"); + return; + } + + StreamHandler streamHandler = RegisterPowerShellStreams(context, submitCode); + try + { + _pwsh.AddScript(code) + .AddCommand(@"Microsoft.DotNet.Interactive.PowerShell\Trace-PipelineObject") + .InvokeAndClearCommands(); + } + catch (Exception e) + { + // If a non-terminating error happened, log it and send back CommandFailed. + // TODO: Should we even output the ErrorRecord? Maybe we should just return + // CommandFailed? + string stringifiedErrorRecord = + _pwsh.AddCommand(CommandUtils.OutStringCmdletInfo) + .AddParameter("InputObject", new ErrorRecord(e, null, ErrorCategory.NotSpecified, null)) + .InvokeAndClearCommands()[0]; + + context.Fail(message: stringifiedErrorRecord); + } + finally + { + UnregisterPowerShellStreams(streamHandler); + } + } + + private void HandleRequestCompletion( + RequestCompletion requestCompletion, + KernelInvocationContext context) + { + var completionRequestReceived = new CompletionRequestReceived(requestCompletion); + + context.Publish(completionRequestReceived); + + var completionList = + GetCompletionList( + requestCompletion.Code, + requestCompletion.CursorPosition); + + context.Publish(new CompletionRequestCompleted(completionList, requestCompletion)); + } + + private void HandleCancelCurrentCommand( + CancelCurrentCommand cancelCurrentCommand, + KernelInvocationContext context) + { + lock (_cancellationSourceLock) + { + _cancellationSource.Cancel(); + _cancellationSource = new CancellationTokenSource(); + if (_pwsh.Runspace.RunspaceAvailability != RunspaceAvailability.Available) + { + _pwsh.Stop(); + } + } + + var reply = new CurrentCommandCancelled(cancelCurrentCommand); + context.Publish(reply); + } + + #endregion + + public static bool IsCompleteSubmission(string code, out ParseError[] errors) + { + // Parse the PowerShell script. If there are any parse errors, check if the input was incomplete. + // We only need to check if the first ParseError has incomplete input. This is consistant with + // what PowerShell itself does today. + Parser.ParseInput(code, out Token[] tokens, out errors); + return errors.Length == 0 || !errors[0].IncompleteInput; + } + + private IEnumerable GetCompletionList( + string code, + int cursorPosition) + { + CommandCompletion completion = CommandCompletion.CompleteInput(code, cursorPosition, null, _pwsh); + + return completion.CompletionMatches.Select(c => new CompletionItem( + displayText: c.CompletionText, + kind: c.ResultType.ToString(), + documentation: c.ToolTip + )); + } + + private StreamHandler RegisterPowerShellStreams( + KernelInvocationContext context, + IKernelCommand command) + { + var streamHandler = new StreamHandler(context, command); + _pwsh.Streams.Debug.DataAdding += streamHandler.DebugDataAdding; + _pwsh.Streams.Warning.DataAdding += streamHandler.WarningDataAdding; + _pwsh.Streams.Error.DataAdding += streamHandler.ErrorDataAdding; + _pwsh.Streams.Verbose.DataAdding += streamHandler.VerboseDataAdding; + _pwsh.Streams.Information.DataAdding += streamHandler.InformationDataAdding; + _pwsh.Streams.Progress.DataAdding += streamHandler.ProgressDataAdding; + return streamHandler; + } + + private void UnregisterPowerShellStreams( + StreamHandler streamHandler) + { + if (streamHandler == null) + { + return; + } + + _pwsh.Streams.Debug.DataAdding -= streamHandler.DebugDataAdding; + _pwsh.Streams.Warning.DataAdding -= streamHandler.WarningDataAdding; + _pwsh.Streams.Error.DataAdding -= streamHandler.ErrorDataAdding; + _pwsh.Streams.Verbose.DataAdding -= streamHandler.VerboseDataAdding; + _pwsh.Streams.Information.DataAdding -= streamHandler.InformationDataAdding; + _pwsh.Streams.Progress.DataAdding -= streamHandler.ProgressDataAdding; + } + } +} diff --git a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs new file mode 100644 index 0000000000..7babf5a2a0 --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs @@ -0,0 +1,199 @@ +// 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; +using static Microsoft.DotNet.Interactive.Formatting.PocketViewTags; + +namespace Microsoft.DotNet.Interactive.PowerShell +{ + using System.Collections.Concurrent; + using System.Management.Automation; + + internal class StreamHandler + { + private static readonly PowerShell _pwsh = PowerShell.Create(); + private static readonly object _pwshLock = new object(); + private readonly KernelInvocationContext _context; + private readonly IKernelCommand _command; + private readonly ConcurrentDictionary _progresses; + + static StreamHandler() + { + SetupRecordFormatters(); + } + + public StreamHandler(KernelInvocationContext context, IKernelCommand command) + { + _context = context; + _command = command; + _progresses = new ConcurrentDictionary(); + } + + 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 async void ProgressDataAdding(object sender, DataAddingEventArgs e) + { + if(e.ItemAdded is ProgressRecord record) + { + if (_progresses.TryGetValue(record.ActivityId, out DisplayedValue displayedValue)) + { + displayedValue.Update(record); + + if (record.RecordType == ProgressRecordType.Completed) + { + _progresses.TryRemove(record.ActivityId, out DisplayedValue _); + } + } + else + { + DisplayedValue dv = await _context.DisplayAsync(record); + _progresses[record.ActivityId] = dv; + } + } + } + + 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); + } + } + + internal static 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 = 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(_pwshLock) + { + var errorDetails = _pwsh.AddCommand("Microsoft.PowerShell.Utility\\Out-String") + .AddParameter("InputObject", record) + .InvokeAndClearCommands(); + result = errorDetails.Single(); + } + + if (result != null) + { + PocketView view = pre(result.Trim()); + writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); + } + }, HtmlFormatter.MimeType); + + Formatter.Register((record, writer) => { + string result = null; + lock(_pwshLock) + { + var errorDetails = _pwsh.AddCommand("Microsoft.PowerShell.Utility\\Out-String") + .AddParameter("InputObject", record) + .InvokeAndClearCommands(); + result = errorDetails.Single(); + } + + if (result != null) + { + writer.WriteLine(result.Trim()); + } + }, PlainTextFormatter.MimeType); + + // InformationRecord + Formatter.Register((record, writer) => { + string prefix = (record.Tags.Count == 1 && + (record.Tags[0] == "__PipelineObject__" || record.Tags[0] == "PSHOST")) ? "" : "INFORMATION: "; + PocketView view = 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__" || record.Tags[0] == "PSHOST")) ? "" : "INFORMATION: "; + writer.WriteLine($"{prefix}{record.MessageData}"); + }, PlainTextFormatter.MimeType); + + // ProgressRecord + Formatter.Register((record, writer) => { + PocketView view = 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 = 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 = 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 a9d9f1985b..f7b01bf4df 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/Microsoft.DotNet.Interactive.Tests/Language.cs b/Microsoft.DotNet.Interactive.Tests/Language.cs index 5dfb7b0711..8eb24c7526 100644 --- a/Microsoft.DotNet.Interactive.Tests/Language.cs +++ b/Microsoft.DotNet.Interactive.Tests/Language.cs @@ -6,6 +6,7 @@ namespace Microsoft.DotNet.Interactive.Tests public enum Language { CSharp = 0, - FSharp = 1 + FSharp = 1, + PowerShell = 2, } } diff --git a/Microsoft.DotNet.Interactive.Tests/LanguageKernelFormattingTests.cs b/Microsoft.DotNet.Interactive.Tests/LanguageKernelFormattingTests.cs index f39341fffd..5e16e1cbc8 100644 --- a/Microsoft.DotNet.Interactive.Tests/LanguageKernelFormattingTests.cs +++ b/Microsoft.DotNet.Interactive.Tests/LanguageKernelFormattingTests.cs @@ -274,5 +274,27 @@ void f() .And .Contain("the-outer-exception"); } + + [Theory()] + [InlineData("Write-Warning 'I am a warning message'", "
WARNING: I am a warning message
")] + [InlineData("Write-Verbose 'I am a verbose message' -Verbose", "
VERBOSE: I am a verbose message
")] + [InlineData("'I am output'", "
I am output
")] + [InlineData("Write-Debug 'I am a debug message' -Debug", "
DEBUG: I am a debug message
")] + [InlineData("Write-Host 'I am an information message'", "
I am an information message
")] + [InlineData("Write-Error 'I am a non-terminating error'", "
Write-Error: I am a non-terminating error
")] + public async Task powershell_stream_formatting(string code, string output) + { + var kernel = CreateKernel(Language.PowerShell); + var command = new SubmitCode(code); + await kernel.SendAsync(command); + + KernelEvents + .Should() + .ContainSingle() + .Which + .FormattedValues + .Should() + .Contain(i => i.Value == output + Environment.NewLine); + } } } \ No newline at end of file diff --git a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTestBase.cs b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTestBase.cs index 4c0aab6e59..d7208c20a6 100644 --- a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTestBase.cs +++ b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTestBase.cs @@ -9,6 +9,7 @@ using Microsoft.DotNet.Interactive.Events; using Microsoft.DotNet.Interactive.FSharp; using Microsoft.DotNet.Interactive.Jupyter; +using Microsoft.DotNet.Interactive.PowerShell; using Pocket; using Recipes; using Xunit.Abstractions; @@ -86,6 +87,7 @@ protected KernelBase CreateKernel(Language language) .UseNugetDirective() .UseKernelHelpers() .UseWho(), + Language.PowerShell => new PowerShellKernel(), _ => throw new InvalidOperationException("Unknown language specified") }; diff --git a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs index e0136b130c..711afdbbe6 100644 --- a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs +++ b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs @@ -3,6 +3,7 @@ using System; using System.Linq; +using System.Management.Automation; using System.Reactive.Linq; using System.Threading.Tasks; using FluentAssertions; @@ -246,6 +247,7 @@ void f() [Theory(Timeout = 45000)] [InlineData(Language.CSharp)] [InlineData(Language.FSharp)] + [InlineData(Language.PowerShell)] public async Task it_returns_diagnostics(Language language) { var kernel = CreateKernel(language); @@ -262,7 +264,11 @@ public async Task it_returns_diagnostics(Language language) { "using System;", "aaaadd" - } + }, + Language.PowerShell => new[] + { + "$x =" + }, }; await SubmitCode(kernel, source); @@ -271,19 +277,26 @@ public async Task it_returns_diagnostics(Language language) { Language.FSharp => "input.fsx (1,1)-(1,7) typecheck error The value or constructor 'aaaadd' is not defined.", Language.CSharp => "(1,1): error CS0103: The name 'aaaadd' does not exist in the current context", + Language.PowerShell => @"At line:1 char:5 ++ $x = ++ ~ +You must provide a value expression following the '=' operator.", }; KernelEvents .Should() .ContainSingle() .Which - .Message + // Unfortunately, PowerShell's ParseError type's ToString() hardcoded a \n which means we have + // mixed newlines in PowerShell... So we replace \r\n with \n so we have consistant newlines. + .Message.Replace("\r\n", "\n") .Should() - .Be(error); + .Be(error.Replace("\r\n", "\n")); } [Theory(Timeout = 45000)] [InlineData(Language.CSharp)] + [InlineData(Language.PowerShell)] // no F# equivalent, because it doesn't have the concept of complete/incomplete submissions public async Task it_can_analyze_incomplete_submissions(Language language) { @@ -291,13 +304,13 @@ public async Task it_can_analyze_incomplete_submissions(Language language) var source = language switch { - Language.CSharp => "var a =" + Language.CSharp => "var a =", + Language.PowerShell => "$a =" }; await SubmitCode(kernel, source, submissionType: SubmissionType.Diagnose); KernelEvents - .Single(e => e is IncompleteCodeSubmissionReceived); KernelEvents @@ -307,6 +320,7 @@ public async Task it_can_analyze_incomplete_submissions(Language language) [Theory(Timeout = 45000)] [InlineData(Language.CSharp)] + [InlineData(Language.PowerShell)] // no F# equivalent, because it doesn't have the concept of complete/incomplete submissions public async Task it_can_analyze_complete_submissions(Language language) { @@ -314,7 +328,8 @@ public async Task it_can_analyze_complete_submissions(Language language) var source = language switch { - Language.CSharp => "25" + Language.CSharp => "25", + Language.PowerShell => "25", }; await SubmitCode(kernel, source, submissionType: SubmissionType.Diagnose); @@ -552,6 +567,7 @@ public async Task kernel_captures_stderr(Language language) [Theory(Skip = "flaky")] [InlineData(Language.CSharp)] [InlineData(Language.FSharp)] + [InlineData(Language.PowerShell)] public async Task it_can_cancel_execution(Language language) { var kernel = CreateKernel(language); @@ -559,7 +575,8 @@ public async Task it_can_cancel_execution(Language language) var source = language switch { Language.FSharp => "System.Threading.Thread.Sleep(3000)\r\n2", - Language.CSharp => "System.Threading.Thread.Sleep(3000);2" + Language.CSharp => "System.Threading.Thread.Sleep(3000);2", + Language.PowerShell => "Start-Sleep -Seconds 3; 2" }; var submitCodeCommand = new SubmitCode(source); @@ -763,14 +780,16 @@ public async Task it_returns_completion_list_for_types(Language language) [Theory(Timeout = 45000)] [InlineData(Language.CSharp)] [InlineData(Language.FSharp)] - public async Task it_returns_completion_list_for_previously_declared_variables(Language language) + [InlineData(Language.PowerShell)] + public async Task it_returns_completion_list_for_previously_declared_items(Language language) { var kernel = CreateKernel(language); var source = language switch { Language.FSharp => @"let alpha = new Random()", - Language.CSharp => @"var alpha = new Random();" + Language.CSharp => @"var alpha = new Random();", + Language.PowerShell => @"function alpha { 5 }", }; await SubmitCode(kernel, source); @@ -829,5 +848,76 @@ public async Task When_submission_is_split_then_CommandHandled_is_published_only .Should() .Be(command); } + + [Fact()] + public async Task PowerShell_streams_handled_in_correct_order() + { + var kernel = CreateKernel(Language.PowerShell); + + var warningMessage = "I am a warning message"; + var verboseMessage = "I am a verbose message"; + var outputMessage = "I am output"; + var debugMessage = "I am a debug message"; + var infoMessage = "I am a information message"; + var errorMessage = "I am a non-terminating error"; + + var command = new SubmitCode($@" +Write-Warning '{warningMessage}' +Write-Verbose '{verboseMessage}' -Verbose +'{outputMessage}' +Write-Debug '{debugMessage}' -Debug +Write-Host '{infoMessage}' +Write-Error '{errorMessage}' +"); + + await kernel.SendAsync(command); + + Assert.Collection(KernelEvents, + e => e.Should().BeOfType(), + e => e.Should().BeOfType(), + e => e.Should().BeOfType().Which + .Value.ToString().Should().Be(warningMessage), + e => e.Should().BeOfType().Which + .Value.ToString().Should().Be(verboseMessage), + e => e.Should().BeOfType().Which + .Value.ToString().Should().Be(outputMessage), + e => e.Should().BeOfType().Which + .Value.ToString().Should().Be(debugMessage), + e => e.Should().BeOfType().Which + .Value.ToString().Should().Be(infoMessage), + e => e.Should().BeOfType().Which + .Value.ToString().Should().Be(errorMessage), + e => e.Should().BeOfType()); + } + + [Fact()] + public async Task PowerShell_progress_sends_updated_display_values() + { + var kernel = CreateKernel(Language.PowerShell); + var command = new SubmitCode(@" +for ($j = 1; $j -le 4; $j++ ) { + Write-Progress -Id 1 -Activity 'Search in Progress' -Status ""$($j*25)% Complete"" -PercentComplete $j; + Start-Sleep -Milliseconds 10 +} +"); + await kernel.SendAsync(command); + + Assert.Collection(KernelEvents, + e => e.Should().BeOfType(), + e => e.Should().BeOfType(), + e => e.Should().BeOfType().Which + .Value.Should().BeOfType().Which + .StatusDescription.Should().Be("25% Complete"), + e => e.Should().BeOfType().Which + .Value.Should().BeOfType().Which + .StatusDescription.Should().Be("50% Complete"), + e => e.Should().BeOfType().Which + .Value.Should().BeOfType().Which + .StatusDescription.Should().Be("75% Complete"), + e => e.Should().BeOfType().Which + .Value.Should().BeOfType().Which + .StatusDescription.Should().Be("100% Complete"), + e => e.Should().BeOfType()); + } } -} \ No newline at end of file +} diff --git a/Microsoft.DotNet.Interactive.Tests/Microsoft.DotNet.Interactive.Tests.csproj b/Microsoft.DotNet.Interactive.Tests/Microsoft.DotNet.Interactive.Tests.csproj index 401f2dbd34..4848ad3da1 100644 --- a/Microsoft.DotNet.Interactive.Tests/Microsoft.DotNet.Interactive.Tests.csproj +++ b/Microsoft.DotNet.Interactive.Tests/Microsoft.DotNet.Interactive.Tests.csproj @@ -48,6 +48,7 @@ + diff --git a/dotnet-interactive.sln b/dotnet-interactive.sln index 6d05c8696c..8eaaf97815 100644 --- a/dotnet-interactive.sln +++ b/dotnet-interactive.sln @@ -39,6 +39,10 @@ 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 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.DotNet.Interactive.PowerShell.Tests", "Microsoft.DotNet.Interactive.PowerShell.Tests\Microsoft.DotNet.Interactive.PowerShell.Tests.csproj", "{30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -241,6 +245,30 @@ 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 + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Debug|x64.ActiveCfg = Debug|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Debug|x64.Build.0 = Debug|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Debug|x86.ActiveCfg = Debug|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Debug|x86.Build.0 = Debug|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Release|Any CPU.Build.0 = Release|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Release|x64.ActiveCfg = Release|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Release|x64.Build.0 = Release|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Release|x86.ActiveCfg = Release|Any CPU + {30DE6920-EA82-4E4F-BFCA-1FF179FAA2DA}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/dotnet-interactive/CommandLine/CommandLineParser.cs b/dotnet-interactive/CommandLine/CommandLineParser.cs index c44d1e6688..9478198842 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; @@ -217,7 +218,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 0000000000..dc5a10f956 --- /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/build-and-install-dotnet-interactive.ps1 b/dotnet-interactive/build-and-install-dotnet-interactive.ps1 index b223b635ec..f5290b855a 100644 --- a/dotnet-interactive/build-and-install-dotnet-interactive.ps1 +++ b/dotnet-interactive/build-and-install-dotnet-interactive.ps1 @@ -19,5 +19,7 @@ if (Test-Path 'env:DisableArcade') { $script:toolVersion = "1.0.44142.42" } -dotnet tool uninstall -g Microsoft.dotnet-interactive +if (Get-Command dotnet-interactive -ErrorAction SilentlyContinue) { + dotnet tool uninstall -g Microsoft.dotnet-interactive +} dotnet tool install -g --add-source "$toolLocation" --version $toolVersion Microsoft.dotnet-interactive diff --git a/dotnet-interactive/dotnet-interactive.csproj b/dotnet-interactive/dotnet-interactive.csproj index 308b3f7f93..565f2fb81b 100644 --- a/dotnet-interactive/dotnet-interactive.csproj +++ b/dotnet-interactive/dotnet-interactive.csproj @@ -68,7 +68,7 @@ all runtime; build; native; contentfiles; analyzers
- +
@@ -79,6 +79,7 @@ + diff --git a/eng/AfterSolutionBuild.targets b/eng/AfterSolutionBuild.targets index 6ccbfdc594..db46129a6d 100644 --- a/eng/AfterSolutionBuild.targets +++ b/eng/AfterSolutionBuild.targets @@ -5,23 +5,46 @@ This file is a terrible hack. - The `dotnet-*.nupkg` packages are never rebuilt to have a stable version because that's handled manually. The fix - is to not allow it to be picked up by the repack targets by temporarily renaming it before the - `PackageReleasePackages` target and restoring it's name after. + The `Microsoft.dotnet-*.nupkg` packages are only built with stable versions and that makes the repack step panic + because there's no expected `-beta.*` infix. The fix is to not allow it to be picked up by the repack targets by + temporarily renaming it before the `PackageReleasePackages` target and restoring it's name after. The same thing + is done for the symbol packages (`*.symbols.nupkg`), too. --> + + + + + + + + + + + + + + + $(TEMP)\$([System.Guid]::NewGuid()) + + + + + + + diff --git a/eng/Signing.props b/eng/Signing.props index 869c7877d6..8a947fdc4a 100644 --- a/eng/Signing.props +++ b/eng/Signing.props @@ -4,7 +4,11 @@ + + + + diff --git a/eng/Versions.props b/eng/Versions.props index a07b501e02..2247b70f73 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -21,28 +21,6 @@ true https://github.com/dotnet/interactive - - false - release - - - - 42424242.42 - <_BuildNumber>$(OfficialBuildId) - <_BuildNumberYY>$(_BuildNumber.Substring(2, 2)) - <_BuildNumberMM>$(_BuildNumber.Substring(4, 2)) - <_BuildNumberDD>$(_BuildNumber.Substring(6, 2)) - <_BuildNumberR>$(_BuildNumber.Substring(9)) - $([MSBuild]::Add($([MSBuild]::Add($([MSBuild]::Multiply($(_BuildNumberYY), 1000)), $([MSBuild]::Multiply($(_BuildNumberMM), 50)))), $(_BuildNumberDD))) - - $(MajorVersion).$(MinorVersion).$(VersionSuffixDateStamp) - $(VersionPrefix).$(_BuildNumberR) - $(VersionPrefix).$(_BuildNumberR) - $(AssemblyVersion) - $(RestoreSources); diff --git a/eng/targets/Settings.props b/eng/targets/Settings.props index 30d64eeb60..5ec05ee7b3 100644 --- a/eng/targets/Settings.props +++ b/eng/targets/Settings.props @@ -5,5 +5,10 @@ Microsoft $(ArtifactsBinDir) $(CopyrightMicrosoft) + + + portable + true +