From 542a675386c951bf14d001bf7321412d3aecd257 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Thu, 23 Jan 2020 13:52:29 -0800 Subject: [PATCH 01/27] add PowerShell subkernel --- .../Protocol/LanguageInfo.cs | 8 + Microsoft.DotNet.Interactive.Jupyter/Shell.cs | 1 + .../Commands/CommandUtils.cs | 19 ++ .../Commands/TracePipelineObjectCommand.cs | 69 ++++ ...osoft.DotNet.Interactive.PowerShell.csproj | 27 ++ ...crosoft.DotNet.Interactive.PowerShell.psd1 | 131 ++++++++ .../PowerShellExtensions.cs | 67 ++++ .../PowerShellKernel.cs | 311 ++++++++++++++++++ .../StreamHandler.cs | 180 ++++++++++ ...rosoft.DotNet.Interactive.Telemetry.csproj | 2 +- dotnet-interactive.sln | 14 + .../CommandLine/CommandLineParser.cs | 4 +- .../kernels/.net-powershell/kernel.json | 12 + dotnet-interactive/dotnet-interactive.csproj | 3 +- 14 files changed, 845 insertions(+), 3 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/Microsoft.DotNet.Interactive.PowerShell.csproj create mode 100644 Microsoft.DotNet.Interactive.PowerShell/Modules/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.psd1 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 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/Commands/CommandUtils.cs b/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs new file mode 100644 index 0000000000..883f7927cc --- /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 0000000000..beb5d8dc1b --- /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 new file mode 100644 index 0000000000..f5bf094799 --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj @@ -0,0 +1,27 @@ + + + + netcoreapp3.1 + $(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..e18c8338b7 --- /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/PowerShellExtensions.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs new file mode 100644 index 0000000000..d297afefbe --- /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 0000000000..779b1f5fdf --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -0,0 +1,311 @@ +// 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.Reflection; +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(); + + public PowerShellKernel() + { + 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 + + 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; + if (!cancellationSource.IsCancellationRequested) + { + await _runspaceSemaphore.WaitAsync(); + try + { + using(var ps = System.Management.Automation.PowerShell.Create(_runspace)) + { + RegisterPowerShellStreams(ps, context, submitCode); + try + { + ps.AddScript(code) + .AddCommand(@"Microsoft.DotNet.Interactive.PowerShell\Trace-PipelineObject") + .InvokeAndClearCommands(); + } + catch (Exception e) + { + string stringifiedErrorRecord = + ps.AddCommand(@"Out-String") + .AddParameter("InputObject", new ErrorRecord(e, null, ErrorCategory.NotSpecified, null)) + .InvokeAndClearCommands()[0]; + + StreamHandler.PublishStreamRecord(stringifiedErrorRecord, context, submitCode); + } + } + } + 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 + { + 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 0000000000..8a70b82ad6 --- /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); + } + } + + 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 = 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__") ? "" : "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__") ? "" : "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 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/dotnet-interactive.sln b/dotnet-interactive.sln index 6d05c8696c..7423469d96 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 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/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 @@ + From 8e41f9ea5596b4515258f2fbcfe8cba76dfcfc3d Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Thu, 23 Jan 2020 15:46:20 -0800 Subject: [PATCH 02/27] simplify code and address feedback --- .../PowerShellExtensions.cs | 14 ++ .../PowerShellKernel.cs | 188 +++++++----------- .../StreamHandler.cs | 25 +-- 3 files changed, 102 insertions(+), 125 deletions(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs index d297afefbe..0ad4b89040 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellExtensions.cs @@ -3,6 +3,7 @@ using System.Collections; using System.Collections.ObjectModel; +using System.Threading.Tasks; namespace Microsoft.DotNet.Interactive.PowerShell { @@ -23,6 +24,19 @@ public static void InvokeAndClearCommands(this PowerShell pwsh) } } + 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 diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index 779b1f5fdf..78b012c615 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -14,7 +14,6 @@ using System.Threading.Tasks; using Microsoft.DotNet.Interactive.Commands; using Microsoft.DotNet.Interactive.Events; -using Microsoft.DotNet.Interactive.Formatting; namespace Microsoft.DotNet.Interactive.PowerShell { @@ -23,23 +22,26 @@ public class PowerShellKernel : KernelBase, IExtensibleKernel internal const string DefaultKernelName = "powershell"; private Runspace _runspace; + private System.Management.Automation.PowerShell _pwsh; private SemaphoreSlim _runspaceSemaphore; private CancellationTokenSource _cancellationSource; private readonly object _cancellationSourceLock = new object(); public PowerShellKernel() { - var iss = InitialSessionState.CreateDefault(); - _runspace = RunspaceFactory.CreateRunspace(iss); + _runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault()); _runspace.Open(); + _pwsh = System.Management.Automation.PowerShell.Create(_runspace); _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"); + psModulePath + Path.PathSeparator + Path.Join( + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), + "Modules")); } #region Overrides @@ -95,10 +97,11 @@ private async Task HandleSubmitCode( 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)) { @@ -109,58 +112,45 @@ private async Task HandleSubmitCode( context.Publish(new IncompleteCodeSubmissionReceived(submitCode)); } + // Do nothing if we get a Diagnose type. if (submitCode.SubmissionType == SubmissionType.Diagnose) { return; } - Exception exception = null; - if (!cancellationSource.IsCancellationRequested) + if (cancellationSource.IsCancellationRequested) { - await _runspaceSemaphore.WaitAsync(); - try - { - using(var ps = System.Management.Automation.PowerShell.Create(_runspace)) - { - RegisterPowerShellStreams(ps, context, submitCode); - try - { - ps.AddScript(code) - .AddCommand(@"Microsoft.DotNet.Interactive.PowerShell\Trace-PipelineObject") - .InvokeAndClearCommands(); - } - catch (Exception e) - { - string stringifiedErrorRecord = - ps.AddCommand(@"Out-String") - .AddParameter("InputObject", new ErrorRecord(e, null, ErrorCategory.NotSpecified, null)) - .InvokeAndClearCommands()[0]; - - StreamHandler.PublishStreamRecord(stringifiedErrorRecord, context, submitCode); - } - } - } - catch (Exception e) - { - exception = e; - } - finally - { - _runspaceSemaphore.Release(); - } + context.Fail(null, "Command cancelled"); + return; } + + // Wait until we have access to the runspace since we only can run one cell at a time. + await _runspaceSemaphore.WaitAsync(); - if (!cancellationSource.IsCancellationRequested) + StreamHandler streamHandler = RegisterPowerShellStreams(context, submitCode); + try { - if (exception != null) - { - string message = null; - context.Publish(new CommandFailed(exception, submitCode, message)); - } + _pwsh.AddScript(code) + .AddCommand(@"Microsoft.DotNet.Interactive.PowerShell\Trace-PipelineObject") + .InvokeAndClearCommands(); } - else + catch (Exception e) { - context.Publish(new CommandFailed(null, submitCode, "Command cancelled")); + // 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(@"Microsoft.PowerShell.Utility\Out-String") + .AddParameter("InputObject", new ErrorRecord(e, null, ErrorCategory.NotSpecified, null)) + .InvokeAndClearCommands()[0]; + + StreamHandler.PublishStreamRecord(stringifiedErrorRecord, context, submitCode); + context.Publish(new CommandFailed(e, submitCode, e.Message)); + } + finally + { + UnregisterPowerShellStreams(streamHandler); + _runspaceSemaphore.Release(); } } @@ -184,13 +174,17 @@ private Task HandleCancelCurrentCommand( CancelCurrentCommand cancelCurrentCommand, KernelInvocationContext context) { - var reply = new CurrentCommandCancelled(cancelCurrentCommand); lock (_cancellationSourceLock) { _cancellationSource.Cancel(); _cancellationSource = new CancellationTokenSource(); + if (_pwsh.Runspace.RunspaceAvailability != RunspaceAvailability.Available) + { + _pwsh.Stop(); + } } + var reply = new CurrentCommandCancelled(cancelCurrentCommand); context.Publish(reply); return Task.CompletedTask; @@ -200,58 +194,11 @@ private Task HandleCancelCurrentCommand( public bool IsCompleteSubmission(string code) { + // Parse the PowerShell script. If there are any parse errors, then we return false. 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) @@ -260,16 +207,16 @@ private async Task> GetCompletionList( 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 - )); - } + // using (var ps = System.Management.Automation.PowerShell.Create(_runspace)) + // { + 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 + )); + // } } finally { @@ -295,17 +242,32 @@ public async Task LoadExtensionsFromDirectory( context); } - private void RegisterPowerShellStreams( - System.Management.Automation.PowerShell powerShell, + private StreamHandler RegisterPowerShellStreams( 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; + _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; + 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; } } } diff --git a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs index 8a70b82ad6..e70f18a2be 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs @@ -5,6 +5,7 @@ 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 { @@ -12,8 +13,8 @@ namespace Microsoft.DotNet.Interactive.PowerShell internal class StreamHandler { - private static readonly PowerShell s_powerShell = PowerShell.Create(); - private static readonly object s_powerShellLock = new object(); + private static readonly PowerShell _pwsh = PowerShell.Create(); + private static readonly object _pwshLock = new object(); KernelInvocationContext _context; IKernelCommand _command; @@ -92,7 +93,7 @@ private static void SetupRecordFormatters() { // DebugRecord Formatter.Register((record, writer) => { - PocketView view = PocketViewTags.pre($"DEBUG: {record.Message}"); + PocketView view = pre($"DEBUG: {record.Message}"); writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); }, HtmlFormatter.MimeType); @@ -103,9 +104,9 @@ private static void SetupRecordFormatters() // ErrorRecord Formatter.Register((record, writer) => { string result = null; - lock(s_powerShellLock) + lock(_pwshLock) { - var errorDetails = s_powerShell.AddCommand("Microsoft.PowerShell.Utility\\Out-String") + var errorDetails = _pwsh.AddCommand("Microsoft.PowerShell.Utility\\Out-String") .AddParameter("InputObject", record) .InvokeAndClearCommands(); result = errorDetails.Single(); @@ -113,16 +114,16 @@ private static void SetupRecordFormatters() if (result != null) { - PocketView view = PocketViewTags.pre(result); + PocketView view = pre(result); writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); } }, HtmlFormatter.MimeType); Formatter.Register((record, writer) => { string result = null; - lock(s_powerShellLock) + lock(_pwshLock) { - var errorDetails = s_powerShell.AddCommand("Microsoft.PowerShell.Utility\\Out-String") + var errorDetails = _pwsh.AddCommand("Microsoft.PowerShell.Utility\\Out-String") .AddParameter("InputObject", record) .InvokeAndClearCommands(); result = errorDetails.Single(); @@ -137,7 +138,7 @@ private static void SetupRecordFormatters() // InformationRecord Formatter.Register((record, writer) => { string prefix = (record.Tags.Count == 1 && record.Tags[0] == "__PipelineObject__") ? "" : "INFORMATION:"; - PocketView view = PocketViewTags.pre($"{prefix} {record.MessageData}"); + PocketView view = pre($"{prefix} {record.MessageData}"); writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); }, HtmlFormatter.MimeType); @@ -148,7 +149,7 @@ private static void SetupRecordFormatters() // ProgressRecord Formatter.Register((record, writer) => { - PocketView view = PocketViewTags.pre($"PROGRESS: {record.StatusDescription}"); + PocketView view = pre($"PROGRESS: {record.StatusDescription}"); writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); }, HtmlFormatter.MimeType); @@ -158,7 +159,7 @@ private static void SetupRecordFormatters() // VerboseRecord Formatter.Register((record, writer) => { - PocketView view = PocketViewTags.pre($"VERBOSE: {record.Message}"); + PocketView view = pre($"VERBOSE: {record.Message}"); writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); }, HtmlFormatter.MimeType); @@ -168,7 +169,7 @@ private static void SetupRecordFormatters() // WarningRecord Formatter.Register((record, writer) => { - PocketView view = PocketViewTags.pre($"WARNING: {record.Message}"); + PocketView view = pre($"WARNING: {record.Message}"); writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); }, HtmlFormatter.MimeType); From 36f2ec3963459b2f3544087f2f2f9aa7b5b8daee Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Thu, 23 Jan 2020 15:56:08 -0800 Subject: [PATCH 03/27] misc cleanup --- .../Commands/TracePipelineObjectCommand.cs | 13 ++++--------- .../PowerShellKernel.cs | 15 +++++++-------- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs index beb5d8dc1b..4822653e7c 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs @@ -3,11 +3,6 @@ // 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; @@ -30,13 +25,13 @@ public sealed class TracePipelineObjectCommand : PSCmdlet [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] public object InputObject { get; set; } - private static PowerShell s_pwsh; + private static PowerShell _pwsh; private SteppablePipeline _stepPipeline; static TracePipelineObjectCommand() { - s_pwsh = PowerShell.Create(); - s_pwsh.AddCommand(CommandUtils.OutStringCmdletInfo).AddParameter("Stream", CommandUtils.BoxedTrue) + _pwsh = PowerShell.Create(); + _pwsh.AddCommand(CommandUtils.OutStringCmdletInfo).AddParameter("Stream", CommandUtils.BoxedTrue) .AddCommand(CommandUtils.WriteInformationCmdletInfo).AddParameter("Tags", "__PipelineObject__"); } @@ -45,7 +40,7 @@ static TracePipelineObjectCommand() /// protected override void BeginProcessing() { - _stepPipeline = s_pwsh.GetSteppablePipeline(); + _stepPipeline = _pwsh.GetSteppablePipeline(); _stepPipeline.Begin(this); } diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index 78b012c615..9dc60eda83 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -3,10 +3,8 @@ 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.Reflection; @@ -14,15 +12,18 @@ 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, IExtensibleKernel { internal const string DefaultKernelName = "powershell"; private Runspace _runspace; - private System.Management.Automation.PowerShell _pwsh; + private PowerShell _pwsh; private SemaphoreSlim _runspaceSemaphore; private CancellationTokenSource _cancellationSource; private readonly object _cancellationSourceLock = new object(); @@ -31,11 +32,12 @@ public PowerShellKernel() { _runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault()); _runspace.Open(); - _pwsh = System.Management.Automation.PowerShell.Create(_runspace); + _pwsh = PowerShell.Create(_runspace); _runspaceSemaphore = new SemaphoreSlim(1, 1); _cancellationSource = new CancellationTokenSource(); Name = DefaultKernelName; + // Add Modules directory that contains the helper modules string psModulePath = Environment.GetEnvironmentVariable("PSModulePath"); Environment.SetEnvironmentVariable("PSModulePath", @@ -140,7 +142,7 @@ private async Task HandleSubmitCode( // TODO: Should we even output the ErrorRecord? Maybe we should just return // CommandFailed? string stringifiedErrorRecord = - _pwsh.AddCommand(@"Microsoft.PowerShell.Utility\Out-String") + _pwsh.AddCommand(CommandUtils.OutStringCmdletInfo) .AddParameter("InputObject", new ErrorRecord(e, null, ErrorCategory.NotSpecified, null)) .InvokeAndClearCommands()[0]; @@ -207,8 +209,6 @@ private async Task> GetCompletionList( try { - // using (var ps = System.Management.Automation.PowerShell.Create(_runspace)) - // { CommandCompletion completion = CommandCompletion.CompleteInput(code, cursorPosition, null, _pwsh); return completion.CompletionMatches.Select(c => new CompletionItem( @@ -216,7 +216,6 @@ private async Task> GetCompletionList( kind: c.ResultType.ToString(), documentation: c.ToolTip )); - // } } finally { From 1e0754a2d97cd3ef9a58c95722a2115d8df3b901 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Thu, 23 Jan 2020 16:14:17 -0800 Subject: [PATCH 04/27] add empty test project like csharp --- ...DotNet.Interactive.PowerShell.Tests.csproj | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Microsoft.DotNet.Interactive.PowerShell.Tests/Microsoft.DotNet.Interactive.PowerShell.Tests.csproj 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..deee121718 --- /dev/null +++ b/Microsoft.DotNet.Interactive.PowerShell.Tests/Microsoft.DotNet.Interactive.PowerShell.Tests.csproj @@ -0,0 +1,19 @@ + + + + netcoreapp3.1 + false + + + + + + + + + + + + + + From b7668fc6ee63e1a846a0b498198f6e2881b52400 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Thu, 23 Jan 2020 16:15:21 -0800 Subject: [PATCH 05/27] Add test project to sln --- dotnet-interactive.sln | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/dotnet-interactive.sln b/dotnet-interactive.sln index 7423469d96..8eaaf97815 100644 --- a/dotnet-interactive.sln +++ b/dotnet-interactive.sln @@ -41,6 +41,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dotnet-interactive.Profiler 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 @@ -255,6 +257,18 @@ Global {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 From df9ef5b01035aa1485418a09e65fe5f4c954fe5c Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Fri, 24 Jan 2020 08:47:46 -0800 Subject: [PATCH 06/27] fix up psd1 and update headers --- .../Commands/CommandUtils.cs | 4 +- .../Commands/TracePipelineObjectCommand.cs | 4 +- ...crosoft.DotNet.Interactive.PowerShell.psd1 | 73 +++++-------------- 3 files changed, 20 insertions(+), 61 deletions(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs b/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs index 883f7927cc..67eceb99b0 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/Commands/CommandUtils.cs @@ -1,7 +1,5 @@ -// -// Copyright (c) Microsoft. All rights reserved. +// 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; diff --git a/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs index 4822653e7c..65ce13dc6c 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs @@ -1,7 +1,5 @@ -// -// Copyright (c) Microsoft. All rights reserved. +// 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 { 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 index e18c8338b7..c6bdb22ff0 100644 --- 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 @@ -1,21 +1,12 @@ -# -# Module manifest for module 'Microsoft.DotNet.Interactive.PowerShell' -# -# Generated by: tyleonha -# -# Generated on: 1/23/2020 -# +# 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. @{ - -# Script module or binary module file associated with this manifest. -# RootModule = '' - # Version number of this module. -ModuleVersion = '0.0.1' +ModuleVersion = '0.1.0' # Supported PSEditions -# CompatiblePSEditions = @() +CompatiblePSEditions = @('Core') # ID used to uniquely identify this module GUID = 'c3ca4cca-fd49-4b1e-a79e-b12afb026068' @@ -27,43 +18,28 @@ Author = 'Microsoft Corporation' CompanyName = 'Microsoft Corporation' # Copyright statement for this module -Copyright = '(c) Microsoft Corporation. All rights reserved.' +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 = '' - -# 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 = '' +PowerShellVersion = '7.0.0' # Modules that must be imported into the global environment prior to importing this module -# RequiredModules = @() +RequiredModules = @() # Assemblies that must be loaded prior to importing this module -# RequiredAssemblies = @() +RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. -# ScriptsToProcess = @() +ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module -# TypesToProcess = @() +TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module -# FormatsToProcess = @() +FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess NestedModules = @('Microsoft.DotNet.Interactive.PowerShell.dll') @@ -80,44 +56,31 @@ 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 = @() + Tags = @('Microsoft', '.NET', 'Jupyter', 'dotnet') # A URL to the license for this module. - # LicenseUri = '' + LicenseUri = 'https://github.com/dotnet/interactive/blob/master/License.txt' # A URL to the main website for this project. - # ProjectUri = '' + ProjectUri = 'https://github.com/dotnet/interactive' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module - # ReleaseNotes = '' + ReleaseNotes = '# v0.1.0 + +Initial release. +' # 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 From ba3d16dd6797f6c7a5673976da9edfb193778eca Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Mon, 27 Jan 2020 09:18:06 -0800 Subject: [PATCH 07/27] PR feedback --- ...DotNet.Interactive.PowerShell.Tests.csproj | 1 + ...osoft.DotNet.Interactive.PowerShell.csproj | 1 + .../PowerShellKernel.cs | 63 ++++++++----------- 3 files changed, 28 insertions(+), 37 deletions(-) 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 index deee121718..2f94dd0760 100644 --- a/Microsoft.DotNet.Interactive.PowerShell.Tests/Microsoft.DotNet.Interactive.PowerShell.Tests.csproj +++ b/Microsoft.DotNet.Interactive.PowerShell.Tests/Microsoft.DotNet.Interactive.PowerShell.Tests.csproj @@ -2,6 +2,7 @@ netcoreapp3.1 + latest false diff --git a/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj b/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj index f5bf094799..47fcc1170a 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj +++ b/Microsoft.DotNet.Interactive.PowerShell/Microsoft.DotNet.Interactive.PowerShell.csproj @@ -2,6 +2,7 @@ netcoreapp3.1 + latest $(NoWarn);2003;CS8002;NU1608; false diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index 9dc60eda83..3d84b77de9 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -22,19 +22,19 @@ public class PowerShellKernel : KernelBase, IExtensibleKernel { internal const string DefaultKernelName = "powershell"; + private readonly object _cancellationSourceLock = new object(); private Runspace _runspace; private PowerShell _pwsh; - private SemaphoreSlim _runspaceSemaphore; private CancellationTokenSource _cancellationSource; - private readonly object _cancellationSourceLock = new object(); + private readonly KernelExtensionAssemblyLoader _extensionLoader; public PowerShellKernel() { _runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault()); _runspace.Open(); _pwsh = PowerShell.Create(_runspace); - _runspaceSemaphore = new SemaphoreSlim(1, 1); _cancellationSource = new CancellationTokenSource(); + _extensionLoader = new KernelExtensionAssemblyLoader(); Name = DefaultKernelName; // Add Modules directory that contains the helper modules @@ -42,7 +42,7 @@ public PowerShellKernel() Environment.SetEnvironmentVariable("PSModulePath", psModulePath + Path.PathSeparator + Path.Join( - Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), + Path.GetDirectoryName(typeof(PowerShellKernel).Assembly.Location), "Modules")); } @@ -61,21 +61,21 @@ protected override Task HandleAsync( case SubmitCode submitCode: submitCode.Handler = async (_, invocationContext) => { - await HandleSubmitCode(submitCode, context); + HandleSubmitCode(submitCode, context); }; break; case RequestCompletion requestCompletion: requestCompletion.Handler = async (_, invocationContext) => { - await HandleRequestCompletion(requestCompletion, invocationContext); + HandleRequestCompletion(requestCompletion, invocationContext); }; break; case CancelCurrentCommand interruptExecution: interruptExecution.Handler = async (_, invocationContext) => { - await HandleCancelCurrentCommand(interruptExecution, invocationContext); + HandleCancelCurrentCommand(interruptExecution, invocationContext); }; break; } @@ -89,7 +89,7 @@ protected override Task HandleAsync( #region Handlers - private async Task HandleSubmitCode( + private void HandleSubmitCode( SubmitCode submitCode, KernelInvocationContext context) { @@ -112,6 +112,7 @@ private async Task HandleSubmitCode( else { context.Publish(new IncompleteCodeSubmissionReceived(submitCode)); + return; } // Do nothing if we get a Diagnose type. @@ -125,9 +126,6 @@ private async Task HandleSubmitCode( context.Fail(null, "Command cancelled"); return; } - - // Wait until we have access to the runspace since we only can run one cell at a time. - await _runspaceSemaphore.WaitAsync(); StreamHandler streamHandler = RegisterPowerShellStreams(context, submitCode); try @@ -152,11 +150,10 @@ private async Task HandleSubmitCode( finally { UnregisterPowerShellStreams(streamHandler); - _runspaceSemaphore.Release(); } } - private async Task HandleRequestCompletion( + private void HandleRequestCompletion( RequestCompletion requestCompletion, KernelInvocationContext context) { @@ -165,14 +162,14 @@ private async Task HandleRequestCompletion( context.Publish(completionRequestReceived); var completionList = - await GetCompletionList( + GetCompletionList( requestCompletion.Code, requestCompletion.CursorPosition); context.Publish(new CompletionRequestCompleted(completionList, requestCompletion)); } - private Task HandleCancelCurrentCommand( + private void HandleCancelCurrentCommand( CancelCurrentCommand cancelCurrentCommand, KernelInvocationContext context) { @@ -188,41 +185,33 @@ private Task HandleCancelCurrentCommand( var reply = new CurrentCommandCancelled(cancelCurrentCommand); context.Publish(reply); - - return Task.CompletedTask; } #endregion public bool IsCompleteSubmission(string code) { - // Parse the PowerShell script. If there are any parse errors, then we return false. + // Parse the PowerShell script. If there are any parse errors, check if the input was incomplete. Parser.ParseInput(code, out Token[] tokens, out ParseError[] errors); - return errors.Length > 0; + return errors.Length == 0 || !errors[0].IncompleteInput; } - private async Task> GetCompletionList( + private IEnumerable GetCompletionList( string code, int cursorPosition) { - await _runspaceSemaphore.WaitAsync(); - - try - { - CommandCompletion completion = CommandCompletion.CompleteInput(code, cursorPosition, null, _pwsh); + 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 - )); - } - finally - { - _runspaceSemaphore.Release(); - } + return completion.CompletionMatches.Select(c => new CompletionItem( + displayText: c.CompletionText, + kind: c.ResultType.ToString(), + documentation: c.ToolTip + )); } + // Load C# extensions that will load types that we want to be available + // in the PowerShell runspace. + // TODO: Does this make sense for PowerShell? public async Task LoadExtensionsFromDirectory( DirectoryInfo directory, KernelInvocationContext context) @@ -235,9 +224,9 @@ public async Task LoadExtensionsFromDirectory( "dotnet", "cs")); - await new KernelExtensionAssemblyLoader().LoadFromAssembliesInDirectory( + await _extensionLoader.LoadFromAssembliesInDirectory( extensionsDirectory, - context.HandlingKernel, + kernel: this, context); } From ff4ac7cfeec0eba048c79664d3a8fc4cbbe9773b Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Mon, 27 Jan 2020 10:16:04 -0800 Subject: [PATCH 08/27] analyzer fixes --- .../PowerShellKernel.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index 3d84b77de9..784163b208 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -59,23 +59,26 @@ protected override Task HandleAsync( switch (command) { case SubmitCode submitCode: - submitCode.Handler = async (_, invocationContext) => + submitCode.Handler = (_, invocationContext) => { HandleSubmitCode(submitCode, context); + return Task.CompletedTask; }; break; case RequestCompletion requestCompletion: - requestCompletion.Handler = async (_, invocationContext) => + requestCompletion.Handler = (_, invocationContext) => { HandleRequestCompletion(requestCompletion, invocationContext); + return Task.CompletedTask; }; break; case CancelCurrentCommand interruptExecution: - interruptExecution.Handler = async (_, invocationContext) => + interruptExecution.Handler = (_, invocationContext) => { HandleCancelCurrentCommand(interruptExecution, invocationContext); + return Task.CompletedTask; }; break; } From f73e071d1e9666c706dbb0ce0d8be34be374ae00 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Mon, 27 Jan 2020 10:26:29 -0800 Subject: [PATCH 09/27] additional comment --- Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index 784163b208..e8f8332620 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -195,6 +195,8 @@ private void HandleCancelCurrentCommand( public bool IsCompleteSubmission(string code) { // 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 ParseError[] errors); return errors.Length == 0 || !errors[0].IncompleteInput; } From 0802ffee80b77185d6dccb0711f6863f21f49042 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Tue, 28 Jan 2020 11:50:29 -0800 Subject: [PATCH 10/27] remove manditory from InputObject --- .../Commands/TracePipelineObjectCommand.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs index 65ce13dc6c..48310b56ea 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs @@ -20,7 +20,7 @@ public sealed class TracePipelineObjectCommand : PSCmdlet /// /// The object from pipeline. /// - [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] + [Parameter(Position = 0, ValueFromPipeline = true)] public object InputObject { get; set; } private static PowerShell _pwsh; From 6c8095e49f5ce47a0e82981a972257606efd66ec Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Tue, 28 Jan 2020 17:02:45 -0800 Subject: [PATCH 11/27] handle parse errors and fix trace-pipelineobjectcommand param --- .../Commands/TracePipelineObjectCommand.cs | 3 ++- .../PowerShellKernel.cs | 20 +++++++++++++------ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs index 48310b56ea..98831c156b 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/Commands/TracePipelineObjectCommand.cs @@ -20,7 +20,8 @@ public sealed class TracePipelineObjectCommand : PSCmdlet /// /// The object from pipeline. /// - [Parameter(Position = 0, ValueFromPipeline = true)] + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)] + [AllowNull] public object InputObject { get; set; } private static PowerShell _pwsh; diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index e8f8332620..4a04bfd6a2 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -108,16 +108,25 @@ private void HandleSubmitCode( // Test is the code we got is actually able to run. var code = submitCode.Code; - if (IsCompleteSubmission(code)) + if (IsCompleteSubmission(code, out ParseError[] parseErrors)) { context.Publish(new CompleteCodeSubmissionReceived(submitCode)); } else { context.Publish(new IncompleteCodeSubmissionReceived(submitCode)); - return; } + // If there were parse errors, publish them and return early. + if (parseErrors.Length > 0) + { + foreach (ParseError parseError in parseErrors) + { + context.Publish(new CommandFailed(null, submitCode, message: parseError.ToString())); + } + return; + } + // Do nothing if we get a Diagnose type. if (submitCode.SubmissionType == SubmissionType.Diagnose) { @@ -147,8 +156,7 @@ private void HandleSubmitCode( .AddParameter("InputObject", new ErrorRecord(e, null, ErrorCategory.NotSpecified, null)) .InvokeAndClearCommands()[0]; - StreamHandler.PublishStreamRecord(stringifiedErrorRecord, context, submitCode); - context.Publish(new CommandFailed(e, submitCode, e.Message)); + context.Fail(message: stringifiedErrorRecord); } finally { @@ -192,12 +200,12 @@ private void HandleCancelCurrentCommand( #endregion - public bool IsCompleteSubmission(string code) + public 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 ParseError[] errors); + Parser.ParseInput(code, out Token[] tokens, out errors); return errors.Length == 0 || !errors[0].IncompleteInput; } From bcf0295c727e4ae596921bb115c655f98dac95de Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Tue, 28 Jan 2020 17:07:35 -0800 Subject: [PATCH 12/27] signing file change --- eng/Signing.props | 3 +++ 1 file changed, 3 insertions(+) diff --git a/eng/Signing.props b/eng/Signing.props index 869c7877d6..5b0bc37ced 100644 --- a/eng/Signing.props +++ b/eng/Signing.props @@ -4,7 +4,10 @@ + + + From 24b0ced1fb0c6b4eb58f02430314dcf0c5cfb358 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Tue, 28 Jan 2020 17:40:12 -0800 Subject: [PATCH 13/27] whitespace --- Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index 4a04bfd6a2..f6348938c9 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -101,7 +101,7 @@ private void HandleSubmitCode( { cancellationSource = _cancellationSource; } - + // Acknowledge that we received the request. var codeSubmissionReceived = new CodeSubmissionReceived(submitCode); context.Publish(codeSubmissionReceived); @@ -125,7 +125,7 @@ private void HandleSubmitCode( context.Publish(new CommandFailed(null, submitCode, message: parseError.ToString())); } return; - } + } // Do nothing if we get a Diagnose type. if (submitCode.SubmissionType == SubmissionType.Diagnose) @@ -174,7 +174,7 @@ private void HandleRequestCompletion( var completionList = GetCompletionList( - requestCompletion.Code, + requestCompletion.Code, requestCompletion.CursorPosition); context.Publish(new CompletionRequestCompleted(completionList, requestCompletion)); From dd2a0c639d3f84ba7b4fcf7fb1d70341280fbc6f Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Tue, 28 Jan 2020 17:45:18 -0800 Subject: [PATCH 14/27] one more signing --- eng/Signing.props | 1 + 1 file changed, 1 insertion(+) diff --git a/eng/Signing.props b/eng/Signing.props index 5b0bc37ced..15dd5a90b6 100644 --- a/eng/Signing.props +++ b/eng/Signing.props @@ -5,6 +5,7 @@ + From d4b3018baf1e95b7b836846ce63acf13508d4e57 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Tue, 28 Jan 2020 18:19:34 -0800 Subject: [PATCH 15/27] change to none --- eng/Signing.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eng/Signing.props b/eng/Signing.props index 15dd5a90b6..8a947fdc4a 100644 --- a/eng/Signing.props +++ b/eng/Signing.props @@ -5,7 +5,7 @@ - + From 3bc49d732fd51e7992fed2d26f5da5f3dd5f6379 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Wed, 29 Jan 2020 10:23:22 -0800 Subject: [PATCH 16/27] remove IExtensibleKernel for now until we understand what we want that to look like --- .../PowerShellKernel.cs | 29 ++----------------- .../build-and-install-dotnet-interactive.ps1 | 4 ++- 2 files changed, 6 insertions(+), 27 deletions(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index f6348938c9..d13a0c503c 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -18,7 +18,7 @@ namespace Microsoft.DotNet.Interactive.PowerShell { using System.Management.Automation; - public class PowerShellKernel : KernelBase, IExtensibleKernel + public class PowerShellKernel : KernelBase { internal const string DefaultKernelName = "powershell"; @@ -120,10 +120,8 @@ private void HandleSubmitCode( // If there were parse errors, publish them and return early. if (parseErrors.Length > 0) { - foreach (ParseError parseError in parseErrors) - { - context.Publish(new CommandFailed(null, submitCode, message: parseError.ToString())); - } + context.Fail(message: string.Join(Environment.NewLine + Environment.NewLine, + parseErrors.Select(pe => pe.ToString()))); return; } @@ -222,27 +220,6 @@ private IEnumerable GetCompletionList( )); } - // Load C# extensions that will load types that we want to be available - // in the PowerShell runspace. - // TODO: Does this make sense for PowerShell? - public async Task LoadExtensionsFromDirectory( - DirectoryInfo directory, - KernelInvocationContext context) - { - var extensionsDirectory = - new DirectoryInfo( - Path.Combine( - directory.FullName, - "interactive-extensions", - "dotnet", - "cs")); - - await _extensionLoader.LoadFromAssembliesInDirectory( - extensionsDirectory, - kernel: this, - context); - } - private StreamHandler RegisterPowerShellStreams( KernelInvocationContext context, IKernelCommand command) 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 From 8d61e78a7e2a93c8fc54067f802d541c946cb321 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Wed, 29 Jan 2020 14:13:19 -0800 Subject: [PATCH 17/27] some tests and small changes to formatting --- .../PowerShellKernel.cs | 2 +- .../StreamHandler.cs | 14 ++-- .../Language.cs | 3 +- .../LanguageKernelTestBase.cs | 2 + .../LanguageKernelTests.cs | 66 ++++++++++++++++--- .../Microsoft.DotNet.Interactive.Tests.csproj | 1 + 6 files changed, 72 insertions(+), 16 deletions(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index d13a0c503c..bf0e53371d 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -198,7 +198,7 @@ private void HandleCancelCurrentCommand( #endregion - public bool IsCompleteSubmission(string code, out ParseError[] errors) + 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 diff --git a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs index e70f18a2be..0141b83cec 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs @@ -114,7 +114,7 @@ private static void SetupRecordFormatters() if (result != null) { - PocketView view = pre(result); + PocketView view = pre(result.Trim()); writer.WriteLine(view.ToDisplayString(HtmlFormatter.MimeType)); } }, HtmlFormatter.MimeType); @@ -131,20 +131,22 @@ private static void SetupRecordFormatters() if (result != null) { - writer.WriteLine(result); + writer.WriteLine(result.Trim()); } }, PlainTextFormatter.MimeType); // InformationRecord Formatter.Register((record, writer) => { - string prefix = (record.Tags.Count == 1 && record.Tags[0] == "__PipelineObject__") ? "" : "INFORMATION:"; - PocketView view = pre($"{prefix} {record.MessageData}"); + 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__") ? "" : "INFORMATION:"; - writer.WriteLine($"{prefix} {record.MessageData}"); + string prefix = (record.Tags.Count == 1 && + (record.Tags[0] == "__PipelineObject__" || record.Tags[0] == "PSHOST")) ? "" : "INFORMATION: "; + writer.WriteLine($"{prefix}{record.MessageData}"); }, PlainTextFormatter.MimeType); // ProgressRecord 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/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..fff7420ad0 100644 --- a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs +++ b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs @@ -246,6 +246,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 +263,11 @@ public async Task it_returns_diagnostics(Language language) { "using System;", "aaaadd" - } + }, + Language.PowerShell => new[] + { + "$x =" + }, }; await SubmitCode(kernel, source); @@ -271,6 +276,10 @@ 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 @@ -284,6 +293,7 @@ public async Task it_returns_diagnostics(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_incomplete_submissions(Language language) { @@ -291,13 +301,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 +317,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 +325,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 +564,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 +572,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 +777,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 +845,39 @@ public async Task When_submission_is_split_then_CommandHandled_is_published_only .Should() .Be(command); } + + [Fact(Timeout = 45000)] + public async Task PowerShell_streams_handled_in_correct_order() + { + var kernel = CreateKernel(Language.PowerShell); + + var command = new SubmitCode(@" +Write-Warning 'I am a warning message' +Write-Verbose 'I am a verbose message' -Verbose +'I am output' +Write-Debug 'I am a debug message' -Debug +Write-Host 'I am an information message' +Write-Error 'I am a non-terminating error' +"); + + await kernel.SendAsync(command); + + Assert.Collection(KernelEvents, + e => e.Should().BeOfType(), + e => e.Should().BeOfType(), + e => e.Should().BeOfType().Which.FormattedValues + .Should().Contain(i => i.Value == "
WARNING: I am a warning message
" + Environment.NewLine), + e => e.Should().BeOfType().Which.FormattedValues + .Should().Contain(i => i.Value == "
VERBOSE: I am a verbose message
" + Environment.NewLine), + e => e.Should().BeOfType().Which.FormattedValues + .Should().Contain(i => i.Value == "
I am output
" + Environment.NewLine), + e => e.Should().BeOfType().Which.FormattedValues + .Should().Contain(i => i.Value == "
DEBUG: I am a debug message
" + Environment.NewLine), + e => e.Should().BeOfType().Which.FormattedValues + .Should().Contain(i => i.Value == "
I am an information message
" + Environment.NewLine), + e => e.Should().BeOfType().Which.FormattedValues + .Should().Contain(i => i.Value == "
Write-Error: I am a non-terminating error
" + Environment.NewLine), + 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 @@ + From 1913ea27bd860516c42dfeed3ecb8cdca7896adf Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Wed, 29 Jan 2020 14:41:30 -0800 Subject: [PATCH 18/27] refactor tests --- .../LanguageKernelFormattingTests.cs | 22 +++++++++ .../LanguageKernelTests.cs | 45 +++++++++++-------- 2 files changed, 48 insertions(+), 19 deletions(-) diff --git a/Microsoft.DotNet.Interactive.Tests/LanguageKernelFormattingTests.cs b/Microsoft.DotNet.Interactive.Tests/LanguageKernelFormattingTests.cs index f39341fffd..b4210efdaa 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(Timeout = 45000)] + [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/LanguageKernelTests.cs b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs index fff7420ad0..04d592cca9 100644 --- a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs +++ b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs @@ -851,13 +851,20 @@ public async Task PowerShell_streams_handled_in_correct_order() { var kernel = CreateKernel(Language.PowerShell); - var command = new SubmitCode(@" -Write-Warning 'I am a warning message' -Write-Verbose 'I am a verbose message' -Verbose -'I am output' -Write-Debug 'I am a debug message' -Debug -Write-Host 'I am an information message' -Write-Error 'I am a non-terminating error' + 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); @@ -865,18 +872,18 @@ public async Task PowerShell_streams_handled_in_correct_order() Assert.Collection(KernelEvents, e => e.Should().BeOfType(), e => e.Should().BeOfType(), - e => e.Should().BeOfType().Which.FormattedValues - .Should().Contain(i => i.Value == "
WARNING: I am a warning message
" + Environment.NewLine), - e => e.Should().BeOfType().Which.FormattedValues - .Should().Contain(i => i.Value == "
VERBOSE: I am a verbose message
" + Environment.NewLine), - e => e.Should().BeOfType().Which.FormattedValues - .Should().Contain(i => i.Value == "
I am output
" + Environment.NewLine), - e => e.Should().BeOfType().Which.FormattedValues - .Should().Contain(i => i.Value == "
DEBUG: I am a debug message
" + Environment.NewLine), - e => e.Should().BeOfType().Which.FormattedValues - .Should().Contain(i => i.Value == "
I am an information message
" + Environment.NewLine), - e => e.Should().BeOfType().Which.FormattedValues - .Should().Contain(i => i.Value == "
Write-Error: I am a non-terminating error
" + Environment.NewLine), + 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()); } } From e3839bbd66da2567306d6f18a7b572584fcefdb7 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Wed, 29 Jan 2020 15:46:51 -0800 Subject: [PATCH 19/27] powershell telemetry & hook up forgotten Progress stream --- Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index bf0e53371d..81f144302c 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -30,6 +30,9 @@ public class PowerShellKernel : KernelBase 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); @@ -230,6 +233,7 @@ private StreamHandler RegisterPowerShellStreams( _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; } @@ -246,6 +250,7 @@ private void UnregisterPowerShellStreams( _pwsh.Streams.Error.DataAdding -= streamHandler.ErrorDataAdding; _pwsh.Streams.Verbose.DataAdding -= streamHandler.VerboseDataAdding; _pwsh.Streams.Information.DataAdding -= streamHandler.InformationDataAdding; + _pwsh.Streams.Progress.DataAdding -= streamHandler.ProgressDataAdding; } } } From 9ae44d5cb338b7ad631a6f9a73de7ca79b23ae83 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Wed, 29 Jan 2020 17:10:42 -0800 Subject: [PATCH 20/27] updating progresses! --- .../StreamHandler.cs | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs index 0141b83cec..0af89a0b30 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs @@ -9,6 +9,7 @@ namespace Microsoft.DotNet.Interactive.PowerShell { + using System.Collections.Concurrent; using System.Management.Automation; internal class StreamHandler @@ -17,6 +18,7 @@ internal class StreamHandler private static readonly object _pwshLock = new object(); KernelInvocationContext _context; IKernelCommand _command; + ConcurrentDictionary _progresses; static StreamHandler() { @@ -27,6 +29,7 @@ public StreamHandler(KernelInvocationContext context, IKernelCommand command) { _context = context; _command = command; + _progresses = new ConcurrentDictionary(); } public void DebugDataAdding(object sender, DataAddingEventArgs e) @@ -53,11 +56,24 @@ public void InformationDataAdding(object sender, DataAddingEventArgs e) } } - public void ProgressDataAdding(object sender, DataAddingEventArgs e) + public async void ProgressDataAdding(object sender, DataAddingEventArgs e) { if(e.ItemAdded is ProgressRecord record) { - PublishStreamRecord(record, _context, _command); + 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; + } } } From 807977cc6fd9cf7f6bc2109b58199aa79e77b6e1 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Thu, 30 Jan 2020 08:37:25 -0800 Subject: [PATCH 21/27] add progress test --- .../LanguageKernelTests.cs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs index 04d592cca9..68fdec639f 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; @@ -886,5 +887,35 @@ public async Task PowerShell_streams_handled_in_correct_order() .Value.ToString().Should().Be(errorMessage), e => e.Should().BeOfType()); } + + [Fact(Timeout = 45000)] + 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()); + } } } From dfcded870f36ca73f7999ce6a59bab74e63362fc Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Thu, 30 Jan 2020 10:43:33 -0800 Subject: [PATCH 22/27] help for ci failures --- .../Microsoft.DotNet.Interactive.nuspec | 2 ++ eng/targets/Settings.props | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec b/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec index 10e2bf3828..34b2a68f3e 100644 --- a/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec +++ b/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec @@ -25,6 +25,8 @@ $CommonFileElements$ + + \ No newline at end of file diff --git a/eng/targets/Settings.props b/eng/targets/Settings.props index 30d64eeb60..7949278a27 100644 --- a/eng/targets/Settings.props +++ b/eng/targets/Settings.props @@ -5,5 +5,11 @@ Microsoft $(ArtifactsBinDir) $(CopyrightMicrosoft) + + + portable + true + snupkg + From 9318b4e0533549dba1af93d4fa373bd42eee20a2 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Thu, 30 Jan 2020 14:34:26 -0800 Subject: [PATCH 23/27] exclude files from symbols packages --- .../Microsoft.DotNet.Interactive.nuspec | 2 -- eng/AfterSolutionBuild.targets | 25 ++++++++++++++++--- eng/Versions.props | 22 ---------------- eng/targets/Settings.props | 3 +-- eng/tools/strip-package-files.ps1 | 25 +++++++++++++++++++ 5 files changed, 48 insertions(+), 29 deletions(-) create mode 100644 eng/tools/strip-package-files.ps1 diff --git a/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec b/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec index 34b2a68f3e..10e2bf3828 100644 --- a/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec +++ b/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec @@ -25,8 +25,6 @@ $CommonFileElements$ - - \ No newline at end of file diff --git a/eng/AfterSolutionBuild.targets b/eng/AfterSolutionBuild.targets index 6ccbfdc594..16d16a28fc 100644 --- a/eng/AfterSolutionBuild.targets +++ b/eng/AfterSolutionBuild.targets @@ -5,23 +5,42 @@ 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. --> + + + + + + + + + + + + + + + $(RepositoryEngineeringDir)tools\strip-package-files.ps1 + -noprofile -executionPolicy RemoteSigned -file "$(StripPackageFilesScriptPath)" -packagePath "%(SymbolPackageWithBadFiles.Identity)" @(SymbolPackageFilesToStrip, ' ') + + 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 7949278a27..5ec05ee7b3 100644 --- a/eng/targets/Settings.props +++ b/eng/targets/Settings.props @@ -6,10 +6,9 @@ $(ArtifactsBinDir) $(CopyrightMicrosoft) - + portable true - snupkg diff --git a/eng/tools/strip-package-files.ps1 b/eng/tools/strip-package-files.ps1 new file mode 100644 index 0000000000..f688a9dc0f --- /dev/null +++ b/eng/tools/strip-package-files.ps1 @@ -0,0 +1,25 @@ +param ( + [string]$packagePath, + [parameter(ValueFromRemainingArguments=$true)][string[]]$filesToStrip +) + +Set-StrictMode -version 2.0 +$ErrorActionPreference = "Stop" + +try { + $packageExpandedPath = "$env:TEMP\" + [System.Guid]::NewGuid() + New-Item -ItemType Directory -Path $packageExpandedPath + Expand-Archive -LiteralPath $packagePath -DestinationPath $packageExpandedPath + $filesToStrip | ForEach-Object { + $fileToStrip = $_ + Remove-Item "$packageExpandedPath\$fileToStrip" + } + Compress-Archive -Path "$packageExpandedPath\*" -DestinationPath $packagePath -Force + Remove-Item -Path $packageExpandedPath -Recurse +} +catch { + Write-Host $_ + Write-Host $_.Exception + Write-Host $_.ScriptStackTrace + exit 1 +} From bc997937c9170ef2955b73aa568c32da9f01aec3 Mon Sep 17 00:00:00 2001 From: "Brett V. Forsgren" Date: Thu, 30 Jan 2020 16:20:01 -0800 Subject: [PATCH 24/27] rewrite package file stripper in pure MSBuild for cross-plat --- eng/AfterSolutionBuild.targets | 10 +++++++--- eng/tools/strip-package-files.ps1 | 25 ------------------------- 2 files changed, 7 insertions(+), 28 deletions(-) delete mode 100644 eng/tools/strip-package-files.ps1 diff --git a/eng/AfterSolutionBuild.targets b/eng/AfterSolutionBuild.targets index 16d16a28fc..db46129a6d 100644 --- a/eng/AfterSolutionBuild.targets +++ b/eng/AfterSolutionBuild.targets @@ -37,10 +37,14 @@
- $(RepositoryEngineeringDir)tools\strip-package-files.ps1 - -noprofile -executionPolicy RemoteSigned -file "$(StripPackageFilesScriptPath)" -packagePath "%(SymbolPackageWithBadFiles.Identity)" @(SymbolPackageFilesToStrip, ' ') + $(TEMP)\$([System.Guid]::NewGuid()) - + + + + + + diff --git a/eng/tools/strip-package-files.ps1 b/eng/tools/strip-package-files.ps1 deleted file mode 100644 index f688a9dc0f..0000000000 --- a/eng/tools/strip-package-files.ps1 +++ /dev/null @@ -1,25 +0,0 @@ -param ( - [string]$packagePath, - [parameter(ValueFromRemainingArguments=$true)][string[]]$filesToStrip -) - -Set-StrictMode -version 2.0 -$ErrorActionPreference = "Stop" - -try { - $packageExpandedPath = "$env:TEMP\" + [System.Guid]::NewGuid() - New-Item -ItemType Directory -Path $packageExpandedPath - Expand-Archive -LiteralPath $packagePath -DestinationPath $packageExpandedPath - $filesToStrip | ForEach-Object { - $fileToStrip = $_ - Remove-Item "$packageExpandedPath\$fileToStrip" - } - Compress-Archive -Path "$packageExpandedPath\*" -DestinationPath $packagePath -Force - Remove-Item -Path $packageExpandedPath -Recurse -} -catch { - Write-Host $_ - Write-Host $_.Exception - Write-Host $_.ScriptStackTrace - exit 1 -} From 1cb39947e8f947e7478b5d3199c5298cf4f29d4a Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Fri, 31 Jan 2020 08:12:44 -0800 Subject: [PATCH 25/27] workaround PowerShell bug --- Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs index 68fdec639f..e1afa08868 100644 --- a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs +++ b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs @@ -287,9 +287,11 @@ public async Task it_returns_diagnostics(Language language) .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)] From ed4dac7cac1b65cec2c2b8459a8b19d1bd456f59 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Fri, 31 Jan 2020 11:21:46 -0800 Subject: [PATCH 26/27] Jon feedback --- .../PowerShellKernel.cs | 3 --- Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs | 8 ++++---- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs index 81f144302c..136f93e603 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs @@ -7,7 +7,6 @@ using System.Linq; 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,7 +25,6 @@ public class PowerShellKernel : KernelBase private Runspace _runspace; private PowerShell _pwsh; private CancellationTokenSource _cancellationSource; - private readonly KernelExtensionAssemblyLoader _extensionLoader; public PowerShellKernel() { @@ -37,7 +35,6 @@ public PowerShellKernel() _runspace.Open(); _pwsh = PowerShell.Create(_runspace); _cancellationSource = new CancellationTokenSource(); - _extensionLoader = new KernelExtensionAssemblyLoader(); Name = DefaultKernelName; // Add Modules directory that contains the helper modules diff --git a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs index 0af89a0b30..7babf5a2a0 100644 --- a/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs +++ b/Microsoft.DotNet.Interactive.PowerShell/StreamHandler.cs @@ -16,9 +16,9 @@ internal class StreamHandler { private static readonly PowerShell _pwsh = PowerShell.Create(); private static readonly object _pwshLock = new object(); - KernelInvocationContext _context; - IKernelCommand _command; - ConcurrentDictionary _progresses; + private readonly KernelInvocationContext _context; + private readonly IKernelCommand _command; + private readonly ConcurrentDictionary _progresses; static StreamHandler() { @@ -173,7 +173,7 @@ private static void SetupRecordFormatters() Formatter.Register((record, writer) => { writer.WriteLine($"PROGRESS: {record.StatusDescription}"); - }, PlainTextFormatter.MimeType); + }, PlainTextFormatter.MimeType); // VerboseRecord Formatter.Register((record, writer) => { From d9f25ab18e8861f90bbe5ac33781928593f267e9 Mon Sep 17 00:00:00 2001 From: Tyler Leonhardt Date: Fri, 31 Jan 2020 11:24:03 -0800 Subject: [PATCH 27/27] remove timeout on new tests --- .../LanguageKernelFormattingTests.cs | 2 +- Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Microsoft.DotNet.Interactive.Tests/LanguageKernelFormattingTests.cs b/Microsoft.DotNet.Interactive.Tests/LanguageKernelFormattingTests.cs index b4210efdaa..5e16e1cbc8 100644 --- a/Microsoft.DotNet.Interactive.Tests/LanguageKernelFormattingTests.cs +++ b/Microsoft.DotNet.Interactive.Tests/LanguageKernelFormattingTests.cs @@ -275,7 +275,7 @@ void f() .Contain("the-outer-exception"); } - [Theory(Timeout = 45000)] + [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
")] diff --git a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs index e1afa08868..711afdbbe6 100644 --- a/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs +++ b/Microsoft.DotNet.Interactive.Tests/LanguageKernelTests.cs @@ -849,7 +849,7 @@ public async Task When_submission_is_split_then_CommandHandled_is_published_only .Be(command); } - [Fact(Timeout = 45000)] + [Fact()] public async Task PowerShell_streams_handled_in_correct_order() { var kernel = CreateKernel(Language.PowerShell); @@ -890,7 +890,7 @@ public async Task PowerShell_streams_handled_in_correct_order() e => e.Should().BeOfType()); } - [Fact(Timeout = 45000)] + [Fact()] public async Task PowerShell_progress_sends_updated_display_values() { var kernel = CreateKernel(Language.PowerShell);