예제 #1
0
        public Task OnLoadAsync(Kernel kernel)
        {
            Formatter.Register <ArchiveReader>(ArchiveMetaData.RegisterForArchiveReader, "text/html");
            Formatter.Register <Archive>(ArchiveMetaData.Register, "text/html");
            Formatter.Register <IFileReader>(FileReaderMetaData.Register, "text/html");
            Formatter.Register <DefaultTerms>(TermsFormatter.Register, "text/html");
            Formatter.Register <IEnumerable <IRow> >(RowFormatter.Register, "text/html");
            Formatter.Register <IGeneratorConfiguration>(GeneratorConfigFormatter.Register, "text/html");

            kernel.AddDirective(new TermsCommand());
            kernel.AddDirective(new DwcaCodegenCommand());

            return(Task.CompletedTask);
        }
예제 #2
0
        public Task OnLoadAsync(Kernel kernel)
        {
            var download = new Command("#!download")
            {
                new Option <Uri>("--uri"),
                new Option <FileInfo>(
                    new[] { "-o", "--output" },
                    parseArgument: ParsePath,
                    isDefault: true)
            };

            download.Handler = CommandHandler.Create(
                (Uri uri, FileInfo output, KernelInvocationContext context) => Download(uri, output, context));

            kernel.AddDirective(download);

            return(Task.CompletedTask);

            FileInfo ParsePath(ArgumentResult argResult)
            {
                if (argResult.Tokens.Any())
                {
                    return(new FileInfo(argResult.Tokens.Single().Value));
                }

                string fileName;

                if (argResult.Parent.Parent.Children["--uri"] is OptionResult uriResult && uriResult.GetValueOrDefault <Uri>() is { } fileUri)
                {
                    fileName = Path.GetFileName(fileUri.LocalPath);
                }
예제 #3
0
        public Task OnLoadAsync(Kernel kernel)
        {
            var inspect = new Command($"#!{INSPECT_COMMAND}", "Inspect the following code in the submission")
            {
                new Option <OptimizationLevel>(
                    new [] { "-c", "--configuration" },
                    getDefaultValue: () => OptimizationLevel.Debug,
                    description: "Build configuration to use. Debug or Release."),
                new Option <SourceCodeKind>(
                    new [] { "-k", "--kind" },
                    getDefaultValue: () => SourceCodeKind.Script,
                    description: "Source code kind. Script or Regular."),
            };

            inspect.Handler = CommandHandler.Create((OptimizationLevel configuration, SourceCodeKind kind, Platform platform, KernelInvocationContext context) => Inspect(configuration, kind, platform, context));

            kernel.AddDirective(inspect);

            KernelInvocationContext.Current?.Display(
                new HtmlString(@"<details><summary>Inspect code compilation details using the <code>#!inspect</code> magic command.</summary>
    <p>The <code>#!inspect</code> magic command allows you to see the C# decompilation, IL, and JIT Asm for the code in a C# cell.</p>
    <img src=""https://user-images.githubusercontent.com/547415/109560515-d5749a00-7a90-11eb-9fa3-51b737345bb4.png"" width=""75%"" />
    </details>"),
                "text/html");

            return(Task.CompletedTask);
        }
        public Task OnLoadAsync(Kernel kernel)
        {
            var loadEnvCommand = new Command("#!env", "Load .env to .NET Notebook.")
            {
                new Option <string>(new[] { "-f", "--file-path" }, "The .env file path"),
                new Option <string>(new[] { "-n", "--var-name" }, "The variable name which contain the .env setting"),
            };

            loadEnvCommand.Handler = CommandHandler.Create(
                async(string filePath, string varName, KernelInvocationContext invocationContext) =>
            {
                invocationContext.Display($"Load {filePath}");

                var filePathString = string.IsNullOrEmpty(filePath) ? string.Empty : Path.Combine(Environment.CurrentDirectory, filePath);
                Console.WriteLine($".env file path: {filePathString}");
                var command = new SubmitCode($"var {varName} = dotenv.net.DotEnv.Fluent().WithEnvFiles(\"{filePathString.Replace(@"\", @"\\")}\").Read();");

                await invocationContext.HandlingKernel.SendAsync(command);
            });

            kernel.AddDirective(loadEnvCommand);

            if (KernelInvocationContext.Current is { } context)
            {
                PocketView view = PocketViewTags.div(
                    PocketViewTags.code(nameof(LoadEnvFileExtension)), " is loaded. It adds loading feature for .env file.", PocketViewTags.br,
                    "Try it by running: ", PocketViewTags.code("#!env -f [file-path] -n [variable-name]")
                    );

                context.Display(view);
            }

            return(Task.CompletedTask);
        }
예제 #5
0
        private void AddDispatcherCommand(Kernel kernel)
        {
            var dispatcherCommand = new Command("#!dispatcher", "Enable or disable running code on the Dispatcher")
            {
                new Option <bool>("--enabled", getDefaultValue: () => true)
            };

            dispatcherCommand.Handler = CommandHandler.Create <bool>(enabled =>
            {
                RunOnDispatcher = enabled;
            });
            kernel.AddDirective(dispatcherCommand);
        }
예제 #6
0
        public Task OnLoadAsync(Kernel kernel)
        {
            Formatter.Register <DateTime>((date, writer) =>
            {
                writer.Write(date.DrawSvgClock());
            }, "text/html");

            Formatter.Register <DateTimeOffset>((date, writer) =>
            {
                writer.Write(date.DrawSvgClock());
            }, "text/html");


            var clockCommand = new Command("#!clock", "Displays a clock showing the current or specified time.")
            {
                new Option <int>(new[] { "-o", "--hour" },
                                 "The position of the hour hand"),
                new Option <int>(new[] { "-m", "--minute" },
                                 "The position of the minute hand"),
                new Option <int>(new[] { "-s", "--second" },
                                 "The position of the second hand")
            };

            clockCommand.Handler = CommandHandler.Create(
                (int hour, int minute, int second, KernelInvocationContext invocationContext) =>
            {
                invocationContext.Display(SvgClock.DrawSvgClock(hour, minute, second));
            });

            kernel.AddDirective(clockCommand);

            if (KernelInvocationContext.Current is { } context)
            {
                PocketView view = div(
                    code(nameof(ClockExtension)),
                    " is loaded. It adds visualizations for ",
                    code(typeof(System.DateTime)),
                    " and ",
                    code(typeof(System.DateTimeOffset)),
                    ". Try it by running: ",
                    code("DateTime.Now"),
                    " or ",
                    code("#!clock -h")
                    );

                context.Display(view);
            }

            return(Task.CompletedTask);
        }
        public Task OnLoadAsync(Kernel kernel)
        {
            var inspect = new Command($"#!{INSPECT_COMMAND}", "Inspect the following code in the submission")
            {
                new Option <OptimizationLevel>(
                    new [] { "-c", "--configuration" },
                    getDefaultValue: () => OptimizationLevel.Debug,
                    description: "Build configuration to use. Debug or Release."),
                new Option <SourceCodeKind>(
                    new [] { "-k", "--kind" },
                    getDefaultValue: () => SourceCodeKind.Script,
                    description: "Source code kind. Script or Regular."),
            };

            inspect.Handler = CommandHandler.Create((OptimizationLevel configuration, SourceCodeKind kind, Platform platform, KernelInvocationContext context) => Inspect(configuration, kind, platform, context));

            kernel.AddDirective(inspect);


            return(Task.CompletedTask);
        }
        public async Task OnLoadAsync(Kernel kernel)
        {
            Formatter <DateTime> .Register((date, writer) =>
            {
                writer.Write(date.DrawSvgClock());
            }, "text/html");

            Formatter <DateTimeOffset> .Register((date, writer) =>
            {
                writer.Write(date.DrawSvgClock());
            }, "text/html");


            var clockCommand = new Command("#!clock", "Displays a clock showing the current or specified time.")
            {
                new Option <int>(new[] { "-o", "--hour" },
                                 "The position of the hour hand"),
                new Option <int>(new[] { "-m", "--minute" },
                                 "The position of the minute hand"),
                new Option <int>(new[] { "-s", "--second" },
                                 "The position of the second hand")
            };

            clockCommand.Handler = CommandHandler.Create(
                async(int hour, int minute, int second, KernelInvocationContext context) =>
            {
                await context.DisplayAsync(SvgClock.DrawSvgClock(hour, minute, second));
            });

            kernel.AddDirective(clockCommand);


            if (KernelInvocationContext.Current is { } context)
            {
                await context.DisplayAsync($"`{nameof(ClockExtension)}` is loaded. It adds visualizations for `System.DateTime` and `System.DateTimeOffset`. Try it by running: `display(DateTime.Now);` or `#!clock -h`", "text/markdown");
            }
        }
예제 #9
0
        public async Task OnLoadAsync(Kernel kernel)
        {
            System.Diagnostics.Debugger.Launch();



            //var kernels = new List<FSharpKernel>();

            //var c = kernel as CompositeKernel;
            //if(c!=null)
            //{
            //    kernels.AddRange(c.ChildKernels.Where(k => k is FSharpKernel).Select(k => (FSharpKernel)k));
            //}

            //if (kernel is FSharpKernel)
            //{
            //    kernels.Add((FSharpKernel)kernel);
            //}
            //foreach(var fs in kernels)
            //{

            //    var allFlags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
            //    var scripty = (Lazy<FSharpScript>)fs.GetType().GetField("script", allFlags).GetValue(fs);
            //    var fsi = scripty.Value.Fsi;

            //    var checkerField = fsi.GetType().GetField("checker", allFlags);
            //    var old = (FSharpChecker)checkerField.GetValue(fsi);

            //    if (!checkers.TryGetValue(old, out var foo))
            //    {
            //        var resolver = (FSharp.Compiler.ReferenceResolver.Resolver)old.GetType().GetField("legacyReferenceResolver", allFlags).GetValue(old);
            //        var nc = FSharpChecker.Create(null, FSharpOption<bool>.Some(true), null, FSharpOption<FSharp.Compiler.ReferenceResolver.Resolver>.Some(resolver), null, null, null, null);
            //        checkerField.SetValue(fsi, nc);
            //        checkers.Add(nc, nc);
            //    }
            //}



            kernel.AddMiddleware((a, b, c) =>
            {
                var fs = b.HandlingKernel as FSharpKernel;
                if (fs != null)
                {
                    Func <string, System.Threading.Tasks.Task> cont = null;
                    string code = null;

                    switch (b.Command)
                    {
                    case SubmitCode v:
                        code = v.Code;
                        cont = n => c(new SubmitCode(n, v.TargetKernelName, v.SubmissionType), b);
                        break;

                    case RequestHoverText v:
                        code = v.Code;
                        cont = n => c(new RequestHoverText(n, v.LinePosition, v.TargetKernelName), b);
                        break;

                    case RequestCompletions v:
                        code = v.Code;
                        cont = n => c(new RequestCompletions(n, v.LinePosition, v.TargetKernelName), b);
                        break;

                    case RequestDiagnostics v:
                        code = v.Code;
                        cont = n => c(new RequestDiagnostics(n, v.TargetKernelName), b);
                        break;
                    }

                    if (code != null)
                    {
                        var allFlags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
                        var scripty  = (Lazy <FSharpScript>)fs.GetType().GetField("script", allFlags).GetValue(fs);
                        var trip     = FSharpAsync.RunSynchronously(scripty.Value.Fsi.ParseAndCheckInteraction(code), FSharpOption <int> .None, FSharpOption <CancellationToken> .None);

                        typeof(FSharpCheckFileResults).GetField("keepAssemblyContents", allFlags).SetValue(trip.Item2, true);

                        var newCode = Adaptify.Compiler.Adaptify.getReplacementCode(Adaptify.Compiler.Log.empty, false, trip.Item2, code);

                        var rx = new System.Text.RegularExpressions.Regex(@"FSI_[0-9][0-9][0-9][0-9]\.");

                        newCode = newCode.Replace("Stdin.", "");
                        newCode = rx.Replace(newCode, "");

                        return(cont(newCode));
                    }
                }
                return(c(a, b));
            });

            Formatter <DateTime> .Register((date, writer) =>
            {
                writer.Write(date.DrawSvgClock());
            }, "text/html");

            Formatter <DateTimeOffset> .Register((date, writer) =>
            {
                writer.Write(date.DrawSvgClock());
            }, "text/html");


            var clockCommand = new Command("#!clock", "Displays a clock showing the current or specified time.")
            {
                new Option <int>(new[] { "-o", "--hour" },
                                 "The position of the hour hand"),
                new Option <int>(new[] { "-m", "--minute" },
                                 "The position of the minute hand"),
                new Option <int>(new[] { "-s", "--second" },
                                 "The position of the second hand")
            };

            clockCommand.Handler = CommandHandler.Create(
                async(int hour, int minute, int second, KernelInvocationContext context) =>
            {
                await context.DisplayAsync(SvgClock.DrawSvgClock(hour, minute, second));
            });

            kernel.AddDirective(clockCommand);

            if (KernelInvocationContext.Current is { } context)
            {
                context.Display(kernel.GetType().FullName);
                await context.DisplayAsync($"asdasdasdasdasd `{nameof(ClockExtension)}` is loaded. It adds visualizations for `System.DateTime` and `System.DateTimeOffset`. Try it by running: `display(DateTime.Now);` or `#!clock -h`", "text/markdown");
            }
        }