Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove --from-result option #2673

Merged
merged 2 commits into from
Feb 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 2 additions & 61 deletions src/Microsoft.DotNet.Interactive.Tests/SetMagicCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,6 @@ namespace Microsoft.DotNet.Interactive.Tests;

public class SetMagicCommandTests
{
[Fact]
public async Task can_set_value_using_return_value()
{
using var kernel = CreateKernel(Language.CSharp);

await kernel.SendAsync(new SubmitCode(@"
#!set --name x --from-result
1+3"));
var (succeeded, valueProduced) = await kernel.TryRequestValueAsync("x");

using var _ = new AssertionScope();

succeeded.Should().BeTrue();
valueProduced.Value.Should().BeEquivalentTo(4);
}

[Fact]
public async Task can_set_value_prompting_user()
Expand Down Expand Up @@ -113,53 +98,9 @@ await composite.SendAsync(new SubmitCode($@"
valueProduced.Value.Should().BeEquivalentTo("456");
}

[Fact]
public async Task set_value_using_return_value_fails_when_successful_code_does_not_produce_return_value()
{
using var kernel = CreateKernel(Language.CSharp);

var results = await kernel.SendAsync(new SubmitCode(@"
#!set --name x --from-result
var num = 1+3;"));

var events = results.KernelEvents.ToSubscribedList();

events.Should().ContainSingle<CommandFailed>()
.Which.Message.Should().Be("The submission did not produce a return value.");

}

[Fact]
public async Task does_not_set_value_if_the_submission_fails()
{
using var kernel = CreateKernel(Language.CSharp);

var results = await kernel.SendAsync(new SubmitCode(@"
#!set --name x --from-result
throw new Exception(""custom error."");"));

var events = results.KernelEvents.ToSubscribedList();

events.Should().ContainSingle<CommandFailed>()
.Which.Message.Should().Contain("System.Exception: custom error.");
}

[Fact]
public async Task set_does_not_allow_from_value_and_from_results_at_the_same_time()
{
using var kernel = CreateKernel(Language.CSharp);

var results = await kernel.SendAsync(new SubmitCode(@"
#!set --name x --from-result --from-value fsharp:y
1+3"));
var events = results.KernelEvents.ToSubscribedList();

events.Should().ContainSingle<CommandFailed>()
.Which.Message.Should().Be("The --from-result and --from-value options cannot be used together.");
}

[Fact]
public async Task set_requires_from_value_or_from_results()
public async Task set_requires_from_option()
{
using var kernel = CreateKernel(Language.CSharp);

Expand All @@ -169,7 +110,7 @@ public async Task set_requires_from_value_or_from_results()
var events = results.KernelEvents.ToSubscribedList();

events.Should().ContainSingle<CommandFailed>()
.Which.Message.Should().Be("At least one of the options [from-result, from-value] must be specified.");
.Which.Message.Should().Be("Option '--from-value' is required.");
}

private static Kernel CreateKernel(Language language)
Expand Down
116 changes: 14 additions & 102 deletions src/Microsoft.DotNet.Interactive/KernelExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,55 +213,18 @@ public static T UseLogMagicCommand<T>(this T kernel)
return kernel;
}



private static void HandleSetMagicCommand<T>(T kernel,
InvocationContext cmdLineContext,
Option<bool> fromResultOption,
Option<string> nameOption,
Option<string> fromValueOption,
Option<string> mimeTypeOption)
Option<string> fromValueOption,
Option<string> mimeTypeOption)
where T : Kernel
{
var fromResult = cmdLineContext.ParseResult.GetValueForOption(fromResultOption);
var valueName = cmdLineContext.ParseResult.GetValueForOption(nameOption);
var mimeType = cmdLineContext.ParseResult.GetValueForOption(mimeTypeOption);
var context = cmdLineContext.GetService<KernelInvocationContext>();


if (fromResult)
{
context.OnComplete((c) =>
{
if (c.IsFailed)
{
return;
}

SetValueFromReturnValueProduced(c);
});
}
else
{
SetValueFromValueProduced(mimeType);
}

void SetValueFromReturnValueProduced(KernelInvocationContext c)
{
var returnValueProducedEvents = new List<ReturnValueProduced>();
using var eventSubscription = context.KernelEvents.OfType<ReturnValueProduced>()
.Subscribe(returnValueProducedEvents.Add);

var returnValueProduced = returnValueProducedEvents.SingleOrDefault();

if (returnValueProduced is { })
{
SendValue(kernel, returnValueProduced.Value, returnValueProduced.FormattedValues.FirstOrDefault(), valueName).GetAwaiter().GetResult();}
else
{
c.Fail(c.Command, message: "The submission did not produce a return value.");
}
}
SetValueFromValueProduced(mimeType);

void SetValueFromValueProduced(string mimetype)
{
Expand All @@ -273,7 +236,6 @@ void SetValueFromValueProduced(string mimetype)

var valueProduced = events.SingleOrDefault();


if (valueProduced is { })
{
var referenceValue = mimetype is not null ? null : valueProduced.Value;
Expand All @@ -282,7 +244,7 @@ void SetValueFromValueProduced(string mimetype)
if (mimeType is not null && formattedValue.MimeType != mimeType)
{
var fromKernelUri = new Uri(valueProduced.RoutingSlip.ToUriArray().First());
var fromKernel = kernel.RootKernel.FindKernel(k => k.KernelInfo.Uri == fromKernelUri|| kernel.KernelInfo.RemoteUri == fromKernelUri
var fromKernel = kernel.RootKernel.FindKernel(k => k.KernelInfo.Uri == fromKernelUri || kernel.KernelInfo.RemoteUri == fromKernelUri
);
var v = GetValue(fromKernel, valueProduced.Name, mimeType).GetAwaiter().GetResult();
formattedValue = v.FormattedValue;
Expand All @@ -293,7 +255,7 @@ void SetValueFromValueProduced(string mimetype)
else
{
var interpolatedValue = cmdLineContext.ParseResult.GetValueForOption(fromValueOption);
SendValue(kernel, interpolatedValue,null, valueName)
SendValue(kernel, interpolatedValue, null, valueName)
.GetAwaiter().GetResult();
}
}
Expand All @@ -313,23 +275,12 @@ public static T UseValueSharing<T>(this T kernel) where T : Kernel

private static void ConfigureAndAddSetMagicCommand<T>(T kernel) where T : Kernel
{
var fromResultOption = new Option<bool>(
"--from-result",
description: "Captures the execution result.");


var fromValueOption = new Option<string>(
"--from-value",
description: "Specifies a value to be stored directly. Specifying @input:value allows you to prompt the user for this value.",
parseArgument: result =>
{
if (SetErrorIfAlsoUsed(fromResultOption, result))
{
return null;
}

return result.Tokens.Single().Value;
});
description: "Specifies a value to be stored directly. Specifying @input:value allows you to prompt the user for this value.")
{
IsRequired = true
};

var mimeTypeOption = new Option<string>("--mime-type", "Share the value as a string formatted to the specified MIME type.")
.AddCompletions(
Expand All @@ -339,16 +290,8 @@ private static void ConfigureAndAddSetMagicCommand<T>(T kernel) where T : Kernel

var nameOption = new Option<string>(
"--name",
description: "This is the name used to declare and set the value in the kernel.",
parseArgument: result =>
{
if (SetErrorIfNoneAreUsed(result, fromResultOption, fromValueOption))
{
return null;
}
description: "This is the name used to declare and set the value in the kernel."

return result.Tokens.Single().Value;
}
)
{
IsRequired = true
Expand All @@ -357,47 +300,16 @@ private static void ConfigureAndAddSetMagicCommand<T>(T kernel) where T : Kernel
var set = new Command("#!set")
{
nameOption,
fromResultOption,
fromValueOption,
mimeTypeOption
};

set.SetHandler(cmdLineContext =>
{
HandleSetMagicCommand(kernel, cmdLineContext, fromResultOption, nameOption, fromValueOption, mimeTypeOption);
HandleSetMagicCommand(kernel, cmdLineContext, nameOption, fromValueOption, mimeTypeOption);
});

kernel.AddDirective(set);

bool SetErrorIfAlsoUsed(Option otherOption, ArgumentResult result)
{
var otherOptionResult = result.FindResultFor(otherOption);

if (otherOptionResult is { })
{
result.ErrorMessage =
$"The {otherOptionResult.Token.Value} and {((OptionResult)result.Parent).Token.Value} options cannot be used together.";

return true;
}

return false;
}

bool SetErrorIfNoneAreUsed(ArgumentResult result, params Option[] options)
{
var otherOptionResults = options.Select(result.FindResultFor).Where(option => option is not null).ToList();

if (otherOptionResults.Count == 0)
{
result.ErrorMessage =
$"At least one of the options [{string.Join(", ", options.Select(o => o.Name))}] must be specified.";

return true;
}

return false;
}
}

private static void ConfigureAndAddShareMagicCommand<T>(T kernel) where T : Kernel
Expand Down Expand Up @@ -502,7 +414,7 @@ internal static async Task GetValueAndSendTo(
{
var valueProduced = await GetValue(fromKernel, fromName, requestedMimeType);

if (valueProduced is { } )
if (valueProduced is { })
{
var declarationName = toName ?? fromName;

Expand All @@ -528,7 +440,7 @@ private static async Task SendValue(Kernel kernel, bool ignoreReferenceValue, Va
}
}

private static async Task SendValue(Kernel kernel,object value, FormattedValue formattedValue,
private static async Task SendValue(Kernel kernel, object value, FormattedValue formattedValue,
string declarationName)
{
if (kernel.SupportsCommandType(typeof(SendValue)))
Expand Down Expand Up @@ -619,7 +531,7 @@ private static async Task DisplayValues(KernelInvocationContext context, bool de
using var __ = result.KernelEvents.OfType<ValueProduced>().Subscribe(e => valueEvents.Add(e));
}

var kernelValues = valueEvents.Select(e => new KernelValue(new KernelValueInfo(e.Name, new FormattedValue(PlainTextFormatter.MimeType, e.Value?.ToDisplayString(PlainTextFormatter.MimeType)) ,e.Value?.GetType()), e.Value, context.HandlingKernel.Name));
var kernelValues = valueEvents.Select(e => new KernelValue(new KernelValueInfo(e.Name, new FormattedValue(PlainTextFormatter.MimeType, e.Value?.ToDisplayString(PlainTextFormatter.MimeType)), e.Value?.GetType()), e.Value, context.HandlingKernel.Name));

var currentVariables = new KernelValues(
kernelValues,
Expand Down