diff --git a/Microsoft.DotNet.Interactive.CSharp/CSharpKernelExtensions.cs b/Microsoft.DotNet.Interactive.CSharp/CSharpKernelExtensions.cs index a25bae7e2a..b5995b9875 100644 --- a/Microsoft.DotNet.Interactive.CSharp/CSharpKernelExtensions.cs +++ b/Microsoft.DotNet.Interactive.CSharp/CSharpKernelExtensions.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.CommandLine; using System.CommandLine.Invocation; +using System.CommandLine.Parsing; using System.Linq; using System.Threading.Tasks; using Microsoft.DotNet.Interactive.Commands; @@ -44,8 +45,20 @@ public static CSharpKernel UseKernelHelpers( public static CSharpKernel UseNugetDirective(this CSharpKernel kernel) { - var packageRefArg = new Argument((SymbolResult result, out PackageReference reference) => - PackageReference.TryParse(result.Token.Value, out reference)) + var packageRefArg = new Argument( + result => + { + var token = result.Tokens.Select(t => t.Value).SingleOrDefault(); + if (PackageReference.TryParse(token, out var reference)) + { + return reference; + } + else + { + result.ErrorMessage = $"Could not parse \"{token}\" as a package reference."; + return null; + } + }) { Name = "package" }; diff --git a/Microsoft.DotNet.Interactive.FSharp/FSharpKernelExtensions.fs b/Microsoft.DotNet.Interactive.FSharp/FSharpKernelExtensions.fs index 1a0d22a92b..477f5c0f44 100644 --- a/Microsoft.DotNet.Interactive.FSharp/FSharpKernelExtensions.fs +++ b/Microsoft.DotNet.Interactive.FSharp/FSharpKernelExtensions.fs @@ -3,6 +3,7 @@ open System open System.CommandLine open System.CommandLine.Invocation +open System.CommandLine.Parsing open System.Runtime.CompilerServices open System.Threading.Tasks open Microsoft.AspNetCore.Html @@ -60,7 +61,7 @@ open System.Linq" let command = Command(detailedName) command.Handler <- CommandHandler.Create( fun (parseResult: ParseResult) (context: KernelInvocationContext) -> - let detailed = parseResult.CommandResult.Token.Value = detailedName + let detailed = parseResult.CommandResult.Command.Name = detailedName match context.Command with | :? SubmitCode -> match context.HandlingKernel with diff --git a/Microsoft.DotNet.Interactive.Formatting/Formatter.cs b/Microsoft.DotNet.Interactive.Formatting/Formatter.cs index cc6fc8030f..5e75c5efff 100644 --- a/Microsoft.DotNet.Interactive.Formatting/Formatter.cs +++ b/Microsoft.DotNet.Interactive.Formatting/Formatter.cs @@ -208,11 +208,10 @@ public static string GetDefaultMimeType() return _defaultMimeType; } - public static string PreferredMimeTypeFor(Type type) - { - return _preferredMimeTypesByType.TryGetValue(type, out var mimeType) ? mimeType : null; - } - + public static string PreferredMimeTypeFor(Type type) => + _preferredMimeTypesByType.TryGetValue(type, out var mimeType) + ? mimeType + : _defaultMimeType; public static string ToDisplayString( this object obj, diff --git a/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.cs b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.cs index d7242b9325..a8d5715d27 100644 --- a/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.cs +++ b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.cs @@ -3,25 +3,20 @@ using System; using System.CommandLine; +using FluentAssertions; using System.Linq; using System.Threading.Tasks; -using FluentAssertions; -using Microsoft.DotNet.Interactive.Commands; using Microsoft.DotNet.Interactive.CSharp; using Microsoft.DotNet.Interactive.Events; -using Microsoft.DotNet.Interactive.FSharp; -using Microsoft.DotNet.Interactive.Formatting; -using Microsoft.DotNet.Interactive.Formatting.Tests; using Microsoft.DotNet.Interactive.Tests; using Pocket; using Xunit; using Xunit.Abstractions; -using static Pocket.Logger; #pragma warning disable 8509 // don't warn on incomplete pattern matches namespace Microsoft.DotNet.Interactive.Jupyter.Tests { - public class MagicCommandTests + public partial class MagicCommandTests { private readonly CompositeDisposable _disposables = new CompositeDisposable(); @@ -30,315 +25,6 @@ public MagicCommandTests(ITestOutputHelper output) _disposables.Add(output.SubscribeToPocketLogger()); } - [Fact] - public async Task lsmagic_lists_registered_magic_commands() - { - using var kernel = new CompositeKernel() - .UseDefaultMagicCommands() - .LogEventsToPocketLogger(); - - kernel.AddDirective(new Command("%%one")); - kernel.AddDirective(new Command("%%two")); - kernel.AddDirective(new Command("%%three")); - - using var events = kernel.KernelEvents.ToSubscribedList(); - - await kernel.SendAsync(new SubmitCode("%lsmagic")); - - events.Should() - .ContainSingle(e => e is DisplayedValueProduced) - .Which - .As() - .Value - .ToDisplayString("text/html") - .Should() - .ContainAll("%lsmagic", "%%one", "%%three", "%%two"); - } - - [Fact] - public async Task lsmagic_lists_registered_magic_commands_in_subkernels() - { - var subkernel1 = new CSharpKernel(); - subkernel1.AddDirective(new Command("%%from-subkernel-1")); - var subkernel2 = new FSharpKernel(); - subkernel2.AddDirective(new Command("%%from-subkernel-2")); - - using var compositeKernel = new CompositeKernel - { - subkernel1, - subkernel2 - } - .UseDefaultMagicCommands() - .LogEventsToPocketLogger(); - - compositeKernel.AddDirective(new Command("%%from-compositekernel")); - - using var events = compositeKernel.KernelEvents.ToSubscribedList(); - - await compositeKernel.SendAsync(new SubmitCode("%lsmagic")); - - var valueProduceds = events.OfType().ToArray(); - - valueProduceds[0].Value - .ToDisplayString("text/html") - .Should() - .ContainAll("%lsmagic", - "%%csharp", - "%%fsharp", - "%%from-compositekernel"); - - valueProduceds[1].Value - .ToDisplayString("text/html") - .Should() - .ContainAll("%lsmagic", - "%%from-subkernel-1"); - valueProduceds[2].Value - .ToDisplayString("text/html") - .Should() - .ContainAll("%lsmagic", - "%%from-subkernel-2"); - } - - [Fact] - public async Task html_emits_string_as_content_within_a_script_element() - { - using var kernel = new CompositeKernel() - .UseDefaultMagicCommands(); - - var html = "hello!"; - - using var events = kernel.KernelEvents.ToSubscribedList(); - - await kernel.SendAsync(new SubmitCode( - $"%%html\n\n{html}")); - - var formatted = - events - .OfType() - .SelectMany(v => v.FormattedValues) - .ToArray(); - - Log.Info(events.ToDisplayString()); - - formatted - .Should() - .ContainSingle(v => - v.MimeType == "text/html" && - v.Value.ToString().Equals(html)); - } - - [Fact] - public async Task javascript_emits_string_as_content_within_a_script_element() - { - using var kernel = new CompositeKernel() - .UseDefaultMagicCommands(); - - var scriptContent = "alert('Hello World!');"; - - using var events = kernel.KernelEvents.ToSubscribedList(); - - await kernel.SendAsync(new SubmitCode( - $"%%javascript\n{scriptContent}")); - - var formatted = - events - .OfType() - .SelectMany(v => v.FormattedValues) - .ToArray(); - - Log.Info(events.ToDisplayString()); - - formatted - .Should() - .ContainSingle(v => - v.MimeType == "text/html" && - v.Value.ToString().Equals($@"")); - } - - - [Fact] - public async Task markdown_renders_markdown_content_as_html() - { - using var kernel = new CompositeKernel() - .UseDefaultMagicCommands(); - - var expectedHtml = @"

Topic!

Content

"; - - using var events = kernel.KernelEvents.ToSubscribedList(); - - await kernel.SendAsync(new SubmitCode( - $"%%markdown\n\n# Topic!\nContent")); - - - var formatted = - events - .OfType() - .SelectMany(v => v.FormattedValues) - .ToArray(); - - formatted - .Should() - .ContainSingle(v => - v.MimeType == "text/html" && - v.Value.ToString().Crunch().Equals(expectedHtml)); - } - - [Fact] - public async Task time_produces_time_elapsed_to_run_the_code_submission() - { - using var kernel = new CompositeKernel - { - new CSharpKernel().UseKernelHelpers() - } - .UseDefaultMagicCommands() - .LogEventsToPocketLogger(); - - using var events = kernel.KernelEvents.ToSubscribedList(); - - await kernel.SendAsync(new SubmitCode( - @" -%%time - -using System.Threading.Tasks; -await Task.Delay(500); -display(""done!""); -")); - - events.Should() - .ContainSingle(e => e is DisplayedValueProduced && - e.As().Value is TimeSpan) - .Which - .As() - .FormattedValues - .Should() - .ContainSingle(v => - v.MimeType == "text/plain" && - v.Value.ToString().StartsWith("Wall time:") && - v.Value.ToString().EndsWith("ms")); - - events.OfType() - .SelectMany(e => e.FormattedValues) - .Should() - .Contain(v => v.Value.Equals("done!")); - } - - [Theory] - [InlineData(Language.CSharp)] - [InlineData(Language.FSharp)] - public async Task whos_lists_the_names_and_values_of_variables_in_scope(Language language) - { - using var baseKernel = language switch - { - Language.CSharp => new CSharpKernel().UseWho() as KernelBase, - Language.FSharp => new FSharpKernel().UseWho(), - }; - using var kernel = new CompositeKernel - { - baseKernel - } - .LogEventsToPocketLogger(); - - using var events = kernel.KernelEvents.ToSubscribedList(); - - var commands = language switch - { - Language.CSharp => new[] - { - "var x = 1;", - "x = 2;", - "var y = \"hi!\";", - "var z = new object[] { x, y };", - }, - Language.FSharp => new[] - { - "let mutable x = 1", - "x <- 2", - "let y = \"hi!\"", - "let z = [| x :> obj; y :> obj |]", - }, - }; - - foreach (var command in commands) - { - await kernel.SendAsync(new SubmitCode(command)); - } - - await kernel.SendAsync(new SubmitCode(@"%whos")); - - events.Should() - .ContainSingle(e => e is DisplayedValueProduced) - .Which - .As() - .FormattedValues - .Should() - .ContainSingle(v => v.MimeType == "text/html") - .Which - .Value - .As() - .Should() - .ContainAll( - "xSystem.Int322", - "ySystem.Stringhi!", - "zSystem.Object[][ 2, hi! ]"); - } - - [Theory] - [InlineData(Language.CSharp)] - [InlineData(Language.FSharp)] - public async Task who_lists_the_names_of_variables_in_scope(Language language) - { - using var baseKernel = language switch - { - Language.CSharp => new CSharpKernel().UseWho() as KernelBase, - Language.FSharp => new FSharpKernel().UseWho(), - }; - using var kernel = new CompositeKernel - { - baseKernel - } - .LogEventsToPocketLogger(); - - using var events = kernel.KernelEvents.ToSubscribedList(); - - var commands = language switch - { - Language.CSharp => new[] - { - "var x = 1;", - "x = 2;", - "var y = \"hi!\";", - "var z = new object[] { x, y };", - }, - Language.FSharp => new[] - { - "let mutable x = 1", - "x <- 2", - "let y = \"hi!\"", - "let z = [| x :> obj; y :> obj |]", - }, - }; - - foreach (var command in commands) - { - await kernel.SendAsync(new SubmitCode(command)); - } - - await kernel.SendAsync(new SubmitCode(@"%who")); - - events.Should() - .ContainSingle(e => e is DisplayedValueProduced) - .Which - .As() - .FormattedValues - .Should() - .ContainSingle(v => v.MimeType == "text/html") - .Which - .Value - .As() - .Should() - .ContainAll("x", "y", "z"); - } - [Fact] public async Task magic_command_parse_errors_are_displayed() { @@ -382,4 +68,4 @@ public async Task magic_command_parse_errors_prevent_code_submission_from_being_ events.Should().NotContain(e => e is ReturnValueProduced); } } -} +} \ No newline at end of file diff --git a/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.html.cs b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.html.cs new file mode 100644 index 0000000000..f47d73c153 --- /dev/null +++ b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.html.cs @@ -0,0 +1,49 @@ +// 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 System.Threading.Tasks; +using FluentAssertions; +using Microsoft.DotNet.Interactive.Commands; +using Microsoft.DotNet.Interactive.Events; +using Microsoft.DotNet.Interactive.Formatting; +using Microsoft.DotNet.Interactive.Tests; +using Pocket; +using Xunit; + +namespace Microsoft.DotNet.Interactive.Jupyter.Tests +{ + public partial class MagicCommandTests + { + public class html + { + [Fact] + public async Task html_emits_string_as_content_within_a_script_element() + { + using var kernel = new CompositeKernel() + .UseDefaultMagicCommands(); + + var html = "hello!"; + + using var events = kernel.KernelEvents.ToSubscribedList(); + + await kernel.SendAsync(new SubmitCode( + $"%%html\n\n{html}")); + + var formatted = + events + .OfType() + .SelectMany(v => v.FormattedValues) + .ToArray(); + + Logger.Log.Info(events.ToDisplayString()); + + formatted + .Should() + .ContainSingle(v => + v.MimeType == "text/html" && + v.Value.ToString().Equals(html)); + } + } + } +} \ No newline at end of file diff --git a/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.javascript.cs b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.javascript.cs new file mode 100644 index 0000000000..c60a1d8b59 --- /dev/null +++ b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.javascript.cs @@ -0,0 +1,49 @@ +// 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 System.Threading.Tasks; +using FluentAssertions; +using Microsoft.DotNet.Interactive.Commands; +using Microsoft.DotNet.Interactive.Events; +using Microsoft.DotNet.Interactive.Formatting; +using Microsoft.DotNet.Interactive.Tests; +using Pocket; +using Xunit; + +namespace Microsoft.DotNet.Interactive.Jupyter.Tests +{ + public partial class MagicCommandTests + { + public class javascript + { + [Fact] + public async Task javascript_emits_string_as_content_within_a_script_element() + { + using var kernel = new CompositeKernel() + .UseDefaultMagicCommands(); + + var scriptContent = "alert('Hello World!');"; + + using var events = kernel.KernelEvents.ToSubscribedList(); + + await kernel.SendAsync(new SubmitCode( + $"%%javascript\n{scriptContent}")); + + var formatted = + events + .OfType() + .SelectMany(v => v.FormattedValues) + .ToArray(); + + Logger.Log.Info(events.ToDisplayString()); + + formatted + .Should() + .ContainSingle(v => + v.MimeType == "text/html" && + v.Value.ToString().Equals($@"")); + } + } + } +} \ No newline at end of file diff --git a/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.lsmagic.cs b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.lsmagic.cs new file mode 100644 index 0000000000..0a9426adcd --- /dev/null +++ b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.lsmagic.cs @@ -0,0 +1,92 @@ +// 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.CommandLine; +using System.Linq; +using System.Threading.Tasks; +using FluentAssertions; +using Microsoft.DotNet.Interactive.Commands; +using Microsoft.DotNet.Interactive.CSharp; +using Microsoft.DotNet.Interactive.Events; +using Microsoft.DotNet.Interactive.Formatting; +using Microsoft.DotNet.Interactive.FSharp; +using Microsoft.DotNet.Interactive.Tests; +using Xunit; + +namespace Microsoft.DotNet.Interactive.Jupyter.Tests +{ + public partial class MagicCommandTests + { + public class lsmagic + { + [Fact] + public async Task lsmagic_lists_registered_magic_commands() + { + using var kernel = new CompositeKernel() + .UseDefaultMagicCommands() + .LogEventsToPocketLogger(); + + kernel.AddDirective(new Command("%%one")); + kernel.AddDirective(new Command("%%two")); + kernel.AddDirective(new Command("%%three")); + + using var events = kernel.KernelEvents.ToSubscribedList(); + + await kernel.SendAsync(new SubmitCode("%lsmagic")); + + events.Should() + .ContainSingle(e => e is DisplayedValueProduced) + .Which + .As() + .Value + .ToDisplayString("text/html") + .Should() + .ContainAll("%lsmagic", "%%one", "%%three", "%%two"); + } + + [Fact] + public async Task lsmagic_lists_registered_magic_commands_in_subkernels() + { + var subkernel1 = new CSharpKernel(); + subkernel1.AddDirective(new Command("%%from-subkernel-1")); + var subkernel2 = new FSharpKernel(); + subkernel2.AddDirective(new Command("%%from-subkernel-2")); + + using var compositeKernel = new CompositeKernel + { + subkernel1, + subkernel2 + } + .UseDefaultMagicCommands() + .LogEventsToPocketLogger(); + + compositeKernel.AddDirective(new Command("%%from-compositekernel")); + + using var events = compositeKernel.KernelEvents.ToSubscribedList(); + + await compositeKernel.SendAsync(new SubmitCode("%lsmagic")); + + var valueProduceds = events.OfType().ToArray(); + + valueProduceds[0].Value + .ToDisplayString("text/html") + .Should() + .ContainAll("%lsmagic", + "%%csharp", + "%%fsharp", + "%%from-compositekernel"); + + valueProduceds[1].Value + .ToDisplayString("text/html") + .Should() + .ContainAll("%lsmagic", + "%%from-subkernel-1"); + valueProduceds[2].Value + .ToDisplayString("text/html") + .Should() + .ContainAll("%lsmagic", + "%%from-subkernel-2"); + } + } + } +} \ No newline at end of file diff --git a/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.markdown.cs b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.markdown.cs new file mode 100644 index 0000000000..44c53deed2 --- /dev/null +++ b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.markdown.cs @@ -0,0 +1,46 @@ +// 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 System.Threading.Tasks; +using FluentAssertions; +using Microsoft.DotNet.Interactive.Commands; +using Microsoft.DotNet.Interactive.Events; +using Microsoft.DotNet.Interactive.Formatting.Tests; +using Microsoft.DotNet.Interactive.Tests; +using Xunit; + +namespace Microsoft.DotNet.Interactive.Jupyter.Tests +{ + public partial class MagicCommandTests + { + public class markdown + { + [Fact] + public async Task markdown_renders_markdown_content_as_html() + { + using var kernel = new CompositeKernel() + .UseDefaultMagicCommands(); + + var expectedHtml = @"

Topic!

Content

"; + + using var events = kernel.KernelEvents.ToSubscribedList(); + + await kernel.SendAsync(new SubmitCode( + $"%%markdown\n\n# Topic!\nContent")); + + var formatted = + events + .OfType() + .SelectMany(v => v.FormattedValues) + .ToArray(); + + formatted + .Should() + .ContainSingle(v => + v.MimeType == "text/html" && + v.Value.ToString().Crunch().Equals(expectedHtml)); + } + } + } +} \ No newline at end of file diff --git a/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.time.cs b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.time.cs new file mode 100644 index 0000000000..bf05c51a7f --- /dev/null +++ b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.time.cs @@ -0,0 +1,60 @@ +// 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.Linq; +using System.Threading.Tasks; +using FluentAssertions; +using Microsoft.DotNet.Interactive.Commands; +using Microsoft.DotNet.Interactive.CSharp; +using Microsoft.DotNet.Interactive.Events; +using Microsoft.DotNet.Interactive.Tests; +using Xunit; + +namespace Microsoft.DotNet.Interactive.Jupyter.Tests +{ + public partial class MagicCommandTests + { + public class time + { + [Fact] + public async Task time_produces_time_elapsed_to_run_the_code_submission() + { + using var kernel = new CompositeKernel + { + new CSharpKernel().UseKernelHelpers() + } + .UseDefaultMagicCommands() + .LogEventsToPocketLogger(); + + using var events = kernel.KernelEvents.ToSubscribedList(); + + await kernel.SendAsync(new SubmitCode( + @" +%%time + +using System.Threading.Tasks; +await Task.Delay(500); +display(""done!""); +")); + + events.Should() + .ContainSingle(e => e is DisplayedValueProduced && + e.As().Value is TimeSpan) + .Which + .As() + .FormattedValues + .Should() + .ContainSingle(v => + v.MimeType == "text/plain" && + v.Value.ToString().StartsWith("Wall time:") && + v.Value.ToString().EndsWith("ms")); + + events.OfType() + .SelectMany(e => e.FormattedValues) + .Should() + .Contain(v => v.Value.Equals("done!")); + } + } + } +} \ No newline at end of file diff --git a/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.who_and_whos.cs b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.who_and_whos.cs new file mode 100644 index 0000000000..d336ba7a77 --- /dev/null +++ b/Microsoft.DotNet.Interactive.Jupyter.Tests/MagicCommandTests.who_and_whos.cs @@ -0,0 +1,138 @@ +// 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.Threading.Tasks; +using FluentAssertions; +using Microsoft.DotNet.Interactive.Commands; +using Microsoft.DotNet.Interactive.CSharp; +using Microsoft.DotNet.Interactive.Events; +using Microsoft.DotNet.Interactive.FSharp; +using Microsoft.DotNet.Interactive.Tests; +using Xunit; + +#pragma warning disable 8509 // don't warn on incomplete pattern matches +namespace Microsoft.DotNet.Interactive.Jupyter.Tests +{ + public partial class MagicCommandTests + { + public class who_and_whos + { + [Theory] + [InlineData(Language.CSharp)] + [InlineData(Language.FSharp)] + public async Task whos_lists_the_names_and_values_of_variables_in_scope(Language language) + { + using var baseKernel = language switch + { + Language.CSharp => new CSharpKernel().UseWho() as KernelBase, + Language.FSharp => new FSharpKernel().UseWho(), + }; + using var kernel = new CompositeKernel + { + baseKernel + } + .LogEventsToPocketLogger(); + + using var events = kernel.KernelEvents.ToSubscribedList(); + + var commands = language switch + { + Language.CSharp => new[] + { + "var x = 1;", + "x = 2;", + "var y = \"hi!\";", + "var z = new object[] { x, y };", + }, + Language.FSharp => new[] + { + "let mutable x = 1", + "x <- 2", + "let y = \"hi!\"", + "let z = [| x :> obj; y :> obj |]", + }, + }; + + foreach (var command in commands) + { + await kernel.SendAsync(new SubmitCode(command)); + } + + await kernel.SendAsync(new SubmitCode(@"%whos")); + + events.Should() + .ContainSingle(e => e is DisplayedValueProduced) + .Which + .As() + .FormattedValues + .Should() + .ContainSingle(v => v.MimeType == "text/html") + .Which + .Value + .As() + .Should() + .ContainAll( + "xSystem.Int322", + "ySystem.Stringhi!", + "zSystem.Object[][ 2, hi! ]"); + } + + [Theory] + [InlineData(Language.CSharp)] + [InlineData(Language.FSharp)] + public async Task who_lists_the_names_of_variables_in_scope(Language language) + { + using var baseKernel = language switch + { + Language.CSharp => new CSharpKernel().UseWho() as KernelBase, + Language.FSharp => new FSharpKernel().UseWho(), + }; + using var kernel = new CompositeKernel + { + baseKernel + } + .LogEventsToPocketLogger(); + + using var events = kernel.KernelEvents.ToSubscribedList(); + + var commands = language switch + { + Language.CSharp => new[] + { + "var x = 1;", + "x = 2;", + "var y = \"hi!\";", + "var z = new object[] { x, y };", + }, + Language.FSharp => new[] + { + "let mutable x = 1", + "x <- 2", + "let y = \"hi!\"", + "let z = [| x :> obj; y :> obj |]", + }, + }; + + foreach (var command in commands) + { + await kernel.SendAsync(new SubmitCode(command)); + } + + await kernel.SendAsync(new SubmitCode(@"%who")); + + events.Should() + .ContainSingle(e => e is DisplayedValueProduced) + .Which + .As() + .FormattedValues + .Should() + .ContainSingle(v => v.MimeType == "text/html") + .Which + .Value + .As() + .Should() + .ContainAll("x", "y", "z"); + } + } + } +} \ No newline at end of file diff --git a/Microsoft.DotNet.Interactive.Jupyter/KernelExtensions.cs b/Microsoft.DotNet.Interactive.Jupyter/KernelExtensions.cs index 0836aa14e8..1745b8eb0d 100644 --- a/Microsoft.DotNet.Interactive.Jupyter/KernelExtensions.cs +++ b/Microsoft.DotNet.Interactive.Jupyter/KernelExtensions.cs @@ -143,7 +143,7 @@ private static T UseLsMagic(this T kernel) { PocketView t = div( h6(directives.KernelName), - pre(directives.Commands.Select(d => d.Name + "\t "))); + pre(directives.Commands.Select(d => d.Name))); t.WriteTo(writer, HtmlEncoder.Default); }, "text/html"); diff --git a/Microsoft.DotNet.Interactive.Telemetry/Microsoft.DotNet.Interactive.Telemetry.csproj b/Microsoft.DotNet.Interactive.Telemetry/Microsoft.DotNet.Interactive.Telemetry.csproj index 57a7185616..c074e60117 100644 --- a/Microsoft.DotNet.Interactive.Telemetry/Microsoft.DotNet.Interactive.Telemetry.csproj +++ b/Microsoft.DotNet.Interactive.Telemetry/Microsoft.DotNet.Interactive.Telemetry.csproj @@ -9,6 +9,6 @@ - + diff --git a/Microsoft.DotNet.Interactive.Telemetry/TelemetryFilter.cs b/Microsoft.DotNet.Interactive.Telemetry/TelemetryFilter.cs index c3c76d696e..8f3ae73f59 100644 --- a/Microsoft.DotNet.Interactive.Telemetry/TelemetryFilter.cs +++ b/Microsoft.DotNet.Interactive.Telemetry/TelemetryFilter.cs @@ -4,7 +4,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.CommandLine; +using System.CommandLine.Parsing; using System.Linq; namespace Microsoft.DotNet.Interactive.Telemetry @@ -61,7 +61,7 @@ private Nullable>> return null; } - return Rules.Select(rule => + return Rules.Select(rule => { if (rule.CommandName == commandName) { @@ -71,13 +71,13 @@ private Nullable>> { return null; } - }).Where(x => x != null).FirstOrDefault(); + }).FirstOrDefault(x => x != null); } /// /// Tries to see if the tokens follow or match the specified command rule. /// - Nullable>> + ImmutableArray>? TryMatchRule(CommandRule rule, IEnumerable tokens, CommandResult commandResult) { var entryItems = ImmutableArray.CreateBuilder>(); diff --git a/Microsoft.DotNet.Interactive/Kernel.cs b/Microsoft.DotNet.Interactive/Kernel.cs index 4257c296a4..51bdabf9f6 100644 --- a/Microsoft.DotNet.Interactive/Kernel.cs +++ b/Microsoft.DotNet.Interactive/Kernel.cs @@ -17,22 +17,9 @@ public static class Kernel public static DisplayedValue display( object value, - string mimeType = HtmlFormatter.MimeType) + string mimeType = null) { - var displayId = DisplayIdGenerator?.Invoke() ?? Guid.NewGuid().ToString(); - - mimeType = Formatter.PreferredMimeTypeFor(value.GetType())?? mimeType; - - var formatted = new FormattedValue( - mimeType, - value.ToDisplayString(mimeType)); - - var kernel = KernelInvocationContext.Current.HandlingKernel; - - Task.Run(() => - kernel.SendAsync(new DisplayValue(value, formatted, displayId))) - .Wait(); - return new DisplayedValue(displayId, mimeType); + return Task.Run(() => KernelInvocationContext.Current.DisplayAsync(value, mimeType)).Result; } public static IHtmlContent HTML(string content) => content.ToHtmlContent(); diff --git a/Microsoft.DotNet.Interactive/KernelInvocationContextExtensions.cs b/Microsoft.DotNet.Interactive/KernelInvocationContextExtensions.cs new file mode 100644 index 0000000000..3afc1bb9b9 --- /dev/null +++ b/Microsoft.DotNet.Interactive/KernelInvocationContextExtensions.cs @@ -0,0 +1,35 @@ +// 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.Threading.Tasks; +using Microsoft.DotNet.Interactive.Commands; +using Microsoft.DotNet.Interactive.Events; +using Microsoft.DotNet.Interactive.Formatting; + +namespace Microsoft.DotNet.Interactive +{ + public static class KernelInvocationContextExtensions + { + public static async Task DisplayAsync( + this KernelInvocationContext context, + object value, + string mimeType = null) + { + var displayId = Kernel.DisplayIdGenerator?.Invoke() ?? + Guid.NewGuid().ToString(); + + mimeType ??= Formatter.PreferredMimeTypeFor(value.GetType()); + + var formatted = new FormattedValue( + mimeType, + value.ToDisplayString(mimeType)); + + var kernel = context.HandlingKernel ?? context.CurrentKernel; + + await kernel.SendAsync(new DisplayValue(value, formatted, displayId)); + + return new DisplayedValue(displayId, mimeType); + } + } +} \ No newline at end of file diff --git a/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.csproj b/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.csproj index 8c5286f1ed..09817075c4 100644 --- a/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.csproj +++ b/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.csproj @@ -16,13 +16,13 @@ 2.9.6 4.3.0 4.3.2 - 0.3.0-alpha.19602.1 + 0.3.0-alpha.20071.1 - + all @@ -33,7 +33,7 @@ - + diff --git a/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec b/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec index ad6731f6d3..10e2bf3828 100644 --- a/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec +++ b/Microsoft.DotNet.Interactive/Microsoft.DotNet.Interactive.nuspec @@ -9,7 +9,7 @@ - + diff --git a/Microsoft.DotNet.Interactive/SubmissionSplitter.cs b/Microsoft.DotNet.Interactive/SubmissionSplitter.cs index 80672a928e..22f9244990 100644 --- a/Microsoft.DotNet.Interactive/SubmissionSplitter.cs +++ b/Microsoft.DotNet.Interactive/SubmissionSplitter.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.CommandLine; using System.CommandLine.Builder; -using System.CommandLine.Invocation; +using System.CommandLine.Parsing; using System.Linq; using Microsoft.DotNet.Interactive.Commands; @@ -55,7 +55,7 @@ public IReadOnlyList SplitSubmission(SubmitCode submitCode) } var runDirective = new AnonymousKernelCommand( - (_, __) => _directiveParser.InvokeAsync(parseResult)); + (_, __) => parseResult.InvokeAsync()); if (command.Name == "#r") { @@ -103,7 +103,7 @@ public IReadOnlyList SplitSubmission(SubmitCode submitCode) hoistedCommands.Add( new AnonymousKernelCommand( - (_, __) => _directiveParser.InvokeAsync(parseResult))); + (_, __) => parseResult.InvokeAsync())); } return hoistedCommands.Concat(commands).ToArray(); diff --git a/dotnet-interactive.Tests/CommandLine/CommandLineParserTests.cs b/dotnet-interactive.Tests/CommandLine/CommandLineParserTests.cs index ae7abd1520..aee8c626a3 100644 --- a/dotnet-interactive.Tests/CommandLine/CommandLineParserTests.cs +++ b/dotnet-interactive.Tests/CommandLine/CommandLineParserTests.cs @@ -2,9 +2,9 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.CommandLine; using System.CommandLine.Binding; -using System.CommandLine.Invocation; +using System.CommandLine.IO; +using System.CommandLine.Parsing; using System.IO; using System.Threading.Tasks; using FluentAssertions; diff --git a/dotnet-interactive.Tests/CommandLine/FirstTimeUseSentinelTests.cs b/dotnet-interactive.Tests/CommandLine/FirstTimeUseSentinelTests.cs index c71043033b..64ec1f8ef4 100644 --- a/dotnet-interactive.Tests/CommandLine/FirstTimeUseSentinelTests.cs +++ b/dotnet-interactive.Tests/CommandLine/FirstTimeUseSentinelTests.cs @@ -2,8 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.CommandLine; -using System.CommandLine.Invocation; +using System.CommandLine.IO; +using System.CommandLine.Parsing; using System.IO; using System.Threading.Tasks; using Microsoft.DotNet.Interactive.App.CommandLine; diff --git a/dotnet-interactive.Tests/CommandLine/TelemetryTests.cs b/dotnet-interactive.Tests/CommandLine/TelemetryTests.cs index 8324ea97f3..be14902f63 100644 --- a/dotnet-interactive.Tests/CommandLine/TelemetryTests.cs +++ b/dotnet-interactive.Tests/CommandLine/TelemetryTests.cs @@ -2,8 +2,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.CommandLine; -using System.CommandLine.Invocation; +using System.CommandLine.IO; +using System.CommandLine.Parsing; using System.IO; using System.Threading.Tasks; using FluentAssertions; diff --git a/dotnet-interactive.Tests/JupyterInstallCommandTests.cs b/dotnet-interactive.Tests/JupyterInstallCommandTests.cs index bd43c9f043..b6298301a7 100644 --- a/dotnet-interactive.Tests/JupyterInstallCommandTests.cs +++ b/dotnet-interactive.Tests/JupyterInstallCommandTests.cs @@ -1,7 +1,7 @@ // 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.CommandLine; +using System.CommandLine.IO; using System.Threading.Tasks; using FluentAssertions; using Xunit; diff --git a/dotnet-interactive.Tests/MagicCommandTests.about.cs b/dotnet-interactive.Tests/MagicCommandTests.about.cs new file mode 100644 index 0000000000..63be5ee6b7 --- /dev/null +++ b/dotnet-interactive.Tests/MagicCommandTests.about.cs @@ -0,0 +1,43 @@ +// 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.Threading.Tasks; +using FluentAssertions; +using Microsoft.DotNet.Interactive.Events; +using Microsoft.DotNet.Interactive.Tests; +using Xunit; + +namespace Microsoft.DotNet.Interactive.App.Tests +{ + public partial class MagicCommandTests + { + public class about + { + [Fact] + public async Task it_shows_the_product_name_and_version_information() + { + using var kernel = new CompositeKernel() + .UseAbout(); + + using var events = kernel.KernelEvents.ToSubscribedList(); + + await kernel.SubmitCodeAsync("#!about"); + + events.Should() + .ContainSingle() + .Which + .FormattedValues + .Should() + .ContainSingle(v => v.MimeType == "text/html") + .Which + .Value + .As() + .Should() + .ContainAll( + ".NET Interactive", + "Version", + "https://github.com/dotnet/interactive"); + } + } + } +} \ No newline at end of file diff --git a/dotnet-interactive/CommandLine/CommandLineParser.cs b/dotnet-interactive/CommandLine/CommandLineParser.cs index ef7b7b876a..1ce626b5e1 100644 --- a/dotnet-interactive/CommandLine/CommandLineParser.cs +++ b/dotnet-interactive/CommandLine/CommandLineParser.cs @@ -5,6 +5,8 @@ using System.CommandLine; using System.CommandLine.Builder; using System.CommandLine.Invocation; +using System.CommandLine.IO; +using System.CommandLine.Parsing; using System.IO; using System.Reactive.Linq; using System.Threading.Tasks; @@ -17,6 +19,7 @@ using Microsoft.DotNet.Interactive.Telemetry; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.FSharp.Core; using Recipes; using CommandHandler = System.CommandLine.Invocation.CommandHandler; @@ -77,23 +80,18 @@ public static Parser Create( var filter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing); void Track(ParseResult o) => telemetry.SendFiltered(filter, o); - var verboseOption = new Option( + var verboseOption = new Option( "--verbose", - "Enable verbose logging to the console") - { - Argument = new Argument() - }; + "Enable verbose logging to the console"); - var logPathOption = new Option( + var logPathOption = new Option( "--log-path", - "Enable file logging to the specified directory") - { - Argument = new Argument - { - Name = "dir" - } - }; + "Enable file logging to the specified directory"); + var defaultKernelOption = new Option( + "--default-kernel", + description: "The default language for the kernel", + defaultValue: "csharp"); var rootCommand = DotnetInteractive(); rootCommand.AddCommand(Jupyter()); @@ -132,22 +130,16 @@ RootCommand DotnetInteractive() Command Jupyter() { - var jupyterCommand = new Command("jupyter", "Starts dotnet-interactive as a Jupyter kernel"); - - var defaultKernelOption = new Option("--default-kernel", "The the default language for the kernel") + var jupyterCommand = new Command("jupyter", "Starts dotnet-interactive as a Jupyter kernel") { - Argument = new Argument(defaultValue: () => "csharp") + defaultKernelOption, + logPathOption, + verboseOption, + new Argument + { + Name = "connection-file" + }.ExistingOnly() }; - - jupyterCommand.AddOption(defaultKernelOption); - jupyterCommand.AddOption(logPathOption); - jupyterCommand.AddOption(verboseOption); - - var connectionFileArgument = new Argument - { - Name = "connection-file" - }.ExistingOnly(); - jupyterCommand.AddArgument(connectionFileArgument); jupyterCommand.Handler = CommandHandler.Create((startupOptions, options, console, context) => { @@ -191,11 +183,6 @@ Command Jupyter() Command KernelServer() { - var defaultKernelOption = new Option("--default-kernel", "The default .NET kernel language for the notebook.") - { - Argument = new Argument(defaultValue: () => "csharp") - }; - var startKernelServerCommand = new Command("kernel-server", "Starts dotnet-interactive with kernel functionality exposed over standard I/O") { defaultKernelOption, @@ -233,7 +220,8 @@ private static IKernel CreateKernel(string defaultKernelName) .UseXplot() .UseMathAndLaTeX() } - .UseDefaultMagicCommands(); + .UseDefaultMagicCommands() + .UseAbout(); kernel.DefaultKernelName = defaultKernelName; kernel.Name = ".NET"; diff --git a/dotnet-interactive/CommandLine/StartupOptions.cs b/dotnet-interactive/CommandLine/StartupOptions.cs index c6fd415c5a..3ffad768ec 100644 --- a/dotnet-interactive/CommandLine/StartupOptions.cs +++ b/dotnet-interactive/CommandLine/StartupOptions.cs @@ -1,8 +1,8 @@ // 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.CommandLine; -using System.CommandLine.Invocation; +using System; +using System.CommandLine.Parsing; using System.IO; using Microsoft.Extensions.DependencyInjection; @@ -10,8 +10,6 @@ namespace Microsoft.DotNet.Interactive.App.CommandLine { public class StartupOptions { - private readonly ParseResult _parseResult; - public static StartupOptions FromCommandLine(string commandLine) { StartupOptions startupOptions = null; @@ -24,10 +22,8 @@ public static StartupOptions FromCommandLine(string commandLine) public StartupOptions( DirectoryInfo logPath = null, - bool verbose = false, - ParseResult parseResult = null) + bool verbose = false) { - _parseResult = parseResult; LogPath = logPath; Verbose = verbose; } diff --git a/dotnet-interactive/JupyterInstallCommand.cs b/dotnet-interactive/JupyterInstallCommand.cs index 4ecd452e72..84e6f04824 100644 --- a/dotnet-interactive/JupyterInstallCommand.cs +++ b/dotnet-interactive/JupyterInstallCommand.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.CommandLine; +using System.CommandLine.IO; using System.IO; using System.IO.Compression; using System.Threading.Tasks; diff --git a/dotnet-interactive/KernelExtensions.cs b/dotnet-interactive/KernelExtensions.cs index a82f363372..591d9dabe9 100644 --- a/dotnet-interactive/KernelExtensions.cs +++ b/dotnet-interactive/KernelExtensions.cs @@ -1,22 +1,61 @@ // 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.CommandLine; +using System.CommandLine.Invocation; using Microsoft.DotNet.Interactive.Formatting; +using Recipes; using XPlot.DotNet.Interactive.KernelExtensions; using XPlot.Plotly; +using static Microsoft.DotNet.Interactive.Formatting.PocketViewTags; namespace Microsoft.DotNet.Interactive.App { public static class KernelExtensions { + public static T UseAbout(this T kernel) + where T : KernelBase + { + var about = new Command("#!about") + { + Handler = CommandHandler.Create( + async context => await context.DisplayAsync(VersionSensor.Version())) + }; + + kernel.AddDirective(about); + + Formatter.Register((info, writer) => + { + // https://github.com/dotnet/swag/tree/master/netlogo + var url = "https://github.com/dotnet/interactive"; + + PocketView html = table( + tbody( + tr( + td( + img[ + src: "https://raw.githubusercontent.com/dotnet/swag/master/netlogo/small-200x198/pngs/msft.net_small_purple.png", + width: "125em"]), + td[style: "line-height:.8em"]( + p[style: "font-size:1.5em"](b(".NET Interactive")), + p("© 2020 Microsoft Corporation"), + p(b("Version: "), info.AssemblyInformationalVersion), + p(b("Build date: "), info.BuildDate), + p(a[href: url](url)) + )) + )); + + writer.Write(html); + }, HtmlFormatter.MimeType); + + return kernel; + } + public static T UseXplot(this T kernel) where T : KernelBase { Formatter.Register( - (chart, writer) => - { - writer.Write(PlotlyChartExtensions.GetHtml(chart)); - }, + (chart, writer) => writer.Write(PlotlyChartExtensions.GetHtml(chart)), HtmlFormatter.MimeType); return kernel; diff --git a/dotnet-interactive/Program.cs b/dotnet-interactive/Program.cs index 07e05d0cea..35ee8c6bd4 100644 --- a/dotnet-interactive/Program.cs +++ b/dotnet-interactive/Program.cs @@ -2,7 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.CommandLine.Invocation; +using System.CommandLine.Parsing; using System.IO; using System.Reflection; using System.Text; diff --git a/dotnet-interactive/dotnet-interactive.csproj b/dotnet-interactive/dotnet-interactive.csproj index 3eb31f83d9..2016caf1b7 100644 --- a/dotnet-interactive/dotnet-interactive.csproj +++ b/dotnet-interactive/dotnet-interactive.csproj @@ -54,7 +54,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all