");
- html.Should().NotContain("concatenated");
- }
-
- [Fact]
- public async Task Package_option_defaults_to_startup_options()
- {
- const string expectedPackage = "console";
- const string expectedPackageVersion = "1.2.3";
-
- var defaultCodeBlockAnnotations = new StartupOptions(
- package: expectedPackage,
- packageVersion: expectedPackageVersion);
- var project = new MarkdownProject(
- new InMemoryDirectoryAccessor(new DirectoryInfo(Directory.GetCurrentDirectory()))
- {
- ("readme.md", @"
-```cs --source-file Program.cs
-```
- "),
- ("Program.cs", "")
- },
- await Default.PackageRegistry.ValueAsync(),
- defaultCodeBlockAnnotations
- );
-
- var html = (await project.GetAllMarkdownFiles()
- .Single()
- .ToHtmlContentAsync())
- .ToString();
-
- html.Should()
- .Contain($"data-trydotnet-package=\"{expectedPackage}\" data-trydotnet-package-version=\"{expectedPackageVersion}\"");
- }
-
- protected async Task
RenderHtml(params (string, string)[] project)
- {
- var directoryAccessor = new InMemoryDirectoryAccessor(new DirectoryInfo(Directory.GetCurrentDirectory()));
-
- foreach (var valueTuple in project)
- {
- directoryAccessor.Add(valueTuple);
- }
-
- var markdownProject = new MarkdownProject(
- directoryAccessor,
- await Default.PackageRegistry.ValueAsync());
-
- var markdownFile = markdownProject.GetAllMarkdownFiles().Single();
- var html = (await markdownFile.ToHtmlContentAsync()).ToString();
-
- _output.WriteLine(html);
-
- return html;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tests/Markdown/MarkdownProjectTests.cs b/MLS.Agent.Tests/Markdown/MarkdownProjectTests.cs
deleted file mode 100644
index 03218bb79..000000000
--- a/MLS.Agent.Tests/Markdown/MarkdownProjectTests.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-// 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.IO;
-using FluentAssertions;
-using System.Linq;
-using Xunit;
-using WorkspaceServer;
-using System.Threading.Tasks;
-using Microsoft.DotNet.Try.Markdown;
-using MLS.Agent.Markdown;
-using WorkspaceServer.Tests;
-using MLS.Agent.Tools;
-using MLS.Agent.Tools.Tests;
-
-namespace MLS.Agent.Tests
-{
- public class MarkdownProjectTests
- {
- public class GetAllMarkdownFiles
- {
- [Fact]
- public async Task Returns_list_of_all_relative_paths_to_all_markdown_files()
- {
- var dirAccessor = new InMemoryDirectoryAccessor()
- {
- ("Readme.md", ""),
- ("Subdirectory/Tutorial.md", ""),
- ("Program.cs", "")
- };
-
- var project = new MarkdownProject(dirAccessor, await Default.PackageRegistry.ValueAsync());
-
- var files = project.GetAllMarkdownFiles();
-
- files.Should().HaveCount(2);
- files.Should().Contain(f => f.Path.Value.Equals("./Readme.md"));
- files.Should().Contain(f => f.Path.Value.Equals("./Subdirectory/Tutorial.md"));
- }
- }
-
- public class TryGetMarkdownFile
- {
- [Fact]
- public async Task Returns_false_for_nonexistent_file()
- {
- var workingDir = TestAssets.SampleConsole;
- var dirAccessor = new InMemoryDirectoryAccessor(workingDir);
- var project = new MarkdownProject(dirAccessor, await Default.PackageRegistry.ValueAsync());
- var path = new RelativeFilePath("DOESNOTEXIST");
-
- project.TryGetMarkdownFile(path, out _).Should().BeFalse();
- }
- }
-
- public class GetAllProjects
- {
- [Fact]
- public async Task Returns_all_projects_referenced_from_all_markdown_files()
- {
- var project = new MarkdownProject(
- new InMemoryDirectoryAccessor(new DirectoryInfo(Directory.GetCurrentDirectory()))
- {
- ("readme.md", @"
-```cs --project ../Project1/Console1.csproj
-```
-```cs --project ../Project2/Console2.csproj
-```
- "),
- ("../Project1/Console1.csproj", @""),
- ("../Project2/Console2.csproj", @"")
- },
- await Default.PackageRegistry.ValueAsync());
-
- var markdownFiles = project.GetAllMarkdownFiles();
-
- var annotatedCodeBlocks = await Task.WhenAll(markdownFiles.Select(f => f.GetAnnotatedCodeBlocks()));
-
- annotatedCodeBlocks
- .SelectMany(f => f)
- .Select(block => block.Annotations)
- .OfType()
- .Select(b => b.Project)
- .Should()
- .Contain(p => p.Directory.Name == "Project1")
- .And
- .Contain(p => p.Directory.Name == "Project2");
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tests/ProjectFilePackageDiscoveryStrategyTests.cs b/MLS.Agent.Tests/ProjectFilePackageDiscoveryStrategyTests.cs
deleted file mode 100644
index 05caefb50..000000000
--- a/MLS.Agent.Tests/ProjectFilePackageDiscoveryStrategyTests.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// 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 FluentAssertions;
-using System.Linq;
-using System.Threading.Tasks;
-using WorkspaceServer.Packaging;
-using WorkspaceServer.Tests;
-using Xunit;
-
-namespace MLS.Agent.Tests
-{
- public class ProjectFilePackageDiscoveryStrategyTests
- {
- [Fact]
- public async Task Discover_package_from_project_file()
- {
- var strategy = new ProjectFilePackageDiscoveryStrategy(false);
- var sampleProject = (await Create.ConsoleWorkspaceCopy()).Directory;
- var projectFile = sampleProject.GetFiles("*.csproj").Single();
- var packageBuilder = await strategy.Locate(new PackageDescriptor(projectFile.FullName));
-
- packageBuilder.PackageName.Should().Be(projectFile.FullName);
- packageBuilder.Directory.FullName.Should().Be(sampleProject.FullName);
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tests/Properties/AssemblyInfo.cs b/MLS.Agent.Tests/Properties/AssemblyInfo.cs
deleted file mode 100644
index d4983a59a..000000000
--- a/MLS.Agent.Tests/Properties/AssemblyInfo.cs
+++ /dev/null
@@ -1,6 +0,0 @@
-// 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 Xunit;
-
-[assembly: CollectionBehavior(DisableTestParallelization = true)]
\ No newline at end of file
diff --git a/MLS.Agent.Tests/ProxyTests.cs b/MLS.Agent.Tests/ProxyTests.cs
deleted file mode 100644
index db833a27c..000000000
--- a/MLS.Agent.Tests/ProxyTests.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// 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 FluentAssertions;
-using System;
-using System.Collections.Generic;
-using System.Net.Http;
-using System.Text;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace MLS.Agent.Tests
-{
- public class ProxyTests
- {
- [Fact]
- public async Task XForwardedPathBase_is_prepended_to_request_url()
- {
- using (var service = new AgentService())
- {
- var message = new HttpRequestMessage(HttpMethod.Get, "/");
- message.Headers.Add("X-Forwarded-PathBase", "/LocalCodeRunner/blazor-console");
-
- var expected = @"
-
-
-
-
-
-
-
- Loading...
-
-
-
-
-
-";
-
- var result = await service.SendAsync(message);
- var content = await result.Content.ReadAsStringAsync();
- content.Should().Be(expected);
-
- }
- }
- }
-}
diff --git a/MLS.Agent.Tests/StringExtensions.cs b/MLS.Agent.Tests/StringExtensions.cs
deleted file mode 100644
index 9a4d664cc..000000000
--- a/MLS.Agent.Tests/StringExtensions.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-// 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 Microsoft.DotNet.Try.Protocol.Tests;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-
-namespace MLS.Agent.Tests
-{
- internal static class StringExtensions
- {
- public static string FormatJson(this string value)
- {
- var s = JToken.Parse(value).ToString(Formatting.Indented);
- return s.EnforceLF();
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tests/WebHostBuilderExtensionTests.cs b/MLS.Agent.Tests/WebHostBuilderExtensionTests.cs
deleted file mode 100644
index c5ad57c9e..000000000
--- a/MLS.Agent.Tests/WebHostBuilderExtensionTests.cs
+++ /dev/null
@@ -1,71 +0,0 @@
-// 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 FluentAssertions;
-using MLS.Agent.CommandLine;
-using System.Linq;
-using System.Net.NetworkInformation;
-using Xunit;
-namespace MLS.Agent.Tests
-{
- public class WebHostBuilderExtensionTests
- {
- [Theory]
- [InlineData(StartupMode.Try)]
- [InlineData(StartupMode.Hosted)]
- public void If_port_is_not_specified_a_free_port_is_returned(StartupMode mode)
- {
- var uri = WebHostBuilderExtensions.GetBrowserLaunchUri(mode, null);
- CheckIfPortIsAvailable(uri.Port).Should().BeTrue();
- }
-
- [Theory]
- [InlineData(StartupMode.Try)]
- [InlineData(StartupMode.Hosted)]
- public void If_a_port_it_specified_it_is_used(StartupMode mode)
- {
- var uri = WebHostBuilderExtensions.GetBrowserLaunchUri(mode, 6000);
- uri.Port.Should().Be(6000);
- }
-
- [Fact]
- public void In_try_mode_host_should_be_localhost()
- {
- var uri = WebHostBuilderExtensions.GetBrowserLaunchUri(StartupMode.Try, 6000);
- uri.Host.Should().Be("localhost");
- }
-
- [Fact]
- public void In_try_mode_scheme_should_be_https()
- {
- var uri = WebHostBuilderExtensions.GetBrowserLaunchUri(StartupMode.Try, 6000);
- uri.Scheme.Should().Be("https");
- }
-
- [Fact]
- public void In_hosted_mode_host_should_be_star()
- {
- var uri = WebHostBuilderExtensions.GetBrowserLaunchUri(StartupMode.Hosted, 6000);
- uri.Host.Should().Be("*");
- }
-
- [Fact]
- public void In_hosted_mode_scheme_should_be_http()
- {
- var uri = WebHostBuilderExtensions.GetBrowserLaunchUri(StartupMode.Hosted, 6000);
- uri.Scheme.Should().Be("http");
- }
-
- private static bool CheckIfPortIsAvailable(ushort port)
- {
- // Evaluate current system tcp connections. This is the same information provided
- // by the netstat command line application, just in .Net strongly-typed object
- // form. We will look through the list, and if our port we would like to use
- // in our TcpClient is occupied, we will set isAvailable to false.
- IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
- TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
-
- return tcpConnInfoArray.FirstOrDefault(tcpi => tcpi.LocalEndPoint.Port == port) == null;
- }
- }
-}
diff --git a/MLS.Agent.Tests/WorkspaceDiscoveryTests.cs b/MLS.Agent.Tests/WorkspaceDiscoveryTests.cs
deleted file mode 100644
index 8987f6d4a..000000000
--- a/MLS.Agent.Tests/WorkspaceDiscoveryTests.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-// 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 Recipes;
-using System;
-using System.CommandLine;
-using System.CommandLine.IO;
-using System.IO;
-using System.Threading.Tasks;
-using Clockwise;
-using FluentAssertions.Extensions;
-using Microsoft.DotNet.Try.Protocol;
-using Microsoft.DotNet.Try.Protocol.Tests;
-using MLS.Agent.CommandLine;
-using WorkspaceServer.Packaging;
-using WorkspaceServer.Tests;
-using Xunit;
-using Xunit.Abstractions;
-using Buffer = Microsoft.DotNet.Try.Protocol.Buffer;
-using File = Microsoft.DotNet.Try.Protocol.File;
-using MLS.Agent.Tools;
-
-namespace MLS.Agent.Tests
-{
- public class WorkspaceDiscoveryTests : ApiViaHttpTestsBase
- {
- public WorkspaceDiscoveryTests(ITestOutputHelper output) : base(output)
- {
- }
-
- [Fact]
- public async Task Local_tool_workspace_can_be_discovered()
- {
- var console = new TestConsole();
- var (packageName, packageLocation) = await CreateLocalTool(console);
-
- var output = Guid.NewGuid().ToString();
- var requestJson = Create.SimpleWorkspaceRequestAsJson(output, packageName);
-
- var response = await CallRun(requestJson, options: new StartupOptions(addPackageSource: new PackageSource(packageLocation.FullName), rootDirectory: new FileSystemDirectoryAccessor(Directory.GetCurrentDirectory())));
- var result = await response
- .EnsureSuccess()
- .DeserializeAs();
-
- result.ShouldSucceedWithOutput(output);
- }
-
- [Fact]
- public async Task Project_file_path_workspace_can_be_discovered_and_run_with_buffer_inlining()
- {
- var package = Create.EmptyWorkspace("a space");
- var build = await Create.NewPackage(package.Name, package.Directory, Create.ConsoleConfiguration) as IHaveADirectory;
-
- var workspace = build.Directory;
- var csproj = workspace.GetFiles("*.csproj")[0];
- var programCs = workspace.GetFiles("*.cs")[0];
-
- var output = Guid.NewGuid().ToString();
- var ws = new Workspace(
- files: new[] { new File(programCs.FullName, SourceCodeProvider.ConsoleProgramSingleRegion) },
- buffers: new[] { new Buffer(new BufferId(programCs.FullName, "alpha"), $"Console.WriteLine(\"{output}\");") },
- workspaceType: csproj.FullName);
-
- var requestJson = new WorkspaceRequest(ws, requestId: "TestRun").ToJson();
-
- var response = await CallRun(requestJson);
- var result = await response
- .EnsureSuccess()
- .DeserializeAs();
-
- result.ShouldSucceedWithOutput(output);
- }
-
- private async Task<(string packageName, DirectoryInfo packageLocation)> CreateLocalTool(IConsole console)
- {
- // Keep project name short to work around max path issues
- var projectName = Guid.NewGuid().ToString("N").Substring(0, 8);
- var build = await Create.NewPackage(projectName, Create.ConsoleConfiguration) as IHaveADirectory;
-
- var ws = await ((ICreateWorkspaceForRun)build).CreateRoslynWorkspaceForRunAsync(new TimeBudget(30.Seconds()));
- var packageLocation = new DirectoryInfo(
- Path.Combine(build.Directory.FullName, "pack-output"));
-
- var packageName = await PackCommand.Do(
- new PackOptions(
- build.Directory,
- outputDirectory: packageLocation,
- enableWasm: false),
- console);
-
- return (packageName, packageLocation);
- }
- }
-}
diff --git a/MLS.Agent.Tests/WorkspaceRequestTests.cs b/MLS.Agent.Tests/WorkspaceRequestTests.cs
deleted file mode 100644
index 7903b47a6..000000000
--- a/MLS.Agent.Tests/WorkspaceRequestTests.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-// 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 FluentAssertions;
-using Microsoft.DotNet.Try.Protocol;
-using Recipes;
-using WorkspaceServer.Tests;
-using Xunit;
-using Buffer = Microsoft.DotNet.Try.Protocol.Buffer;
-
-namespace MLS.Agent.Tests
-{
- public class WorkspaceRequestTests
- {
- [Fact]
- public void webrequest_must_have_verb()
- {
- var action = new Action(() =>
- {
- var wr = new HttpRequest(@"/handler", string.Empty);
- });
- action.Should().Throw();
- }
-
- [Fact]
- public void webrequest_must_have_relative_url()
- {
- var action = new Action(() =>
- {
- var wr = new HttpRequest(@"http://www.microsoft.com", "post");
- });
- action.Should().Throw();
- }
-
- [Fact]
- public void When_ActiveBufferId_is_not_specified_and_there_is_only_one_buffer_then_it_returns_that_buffers_id()
- {
- var request = new WorkspaceRequest(
- new Workspace(
- buffers: new[]
- {
- new Buffer("the.only.buffer.cs", "its content", 123)
- }),
- requestId: "TestRun");
-
- request.ActiveBufferId.Should().Be(BufferId.Parse("the.only.buffer.cs"));
- }
-
- [Fact]
- public void WorkspaceRequest_deserializes_from_JSON()
- {
- var (processed, position) = CodeManipulation.ProcessMarkup("Console.WriteLine($$)");
-
- var original = new WorkspaceRequest(
- activeBufferId: BufferId.Parse("default.cs"),
- workspace: Workspace.FromSource(
- processed,
- "script",
- id: "default.cs",
- position: position), requestId: "TestRun");
-
- var json = original.ToJson();
-
- var deserialized = json.FromJsonTo();
-
- deserialized.Should().BeEquivalentTo(original);
- }
- }
-}
diff --git a/MLS.Agent.Tests/index.ts b/MLS.Agent.Tests/index.ts
deleted file mode 100644
index a2b882f99..000000000
--- a/MLS.Agent.Tests/index.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import * as path from "path";
-import * as fs from "fs";
-
-//Read the expected approval file as json and return the result
-export function GetExpectedResultASJSON(filename: string) {
- let testDir = path.resolve(process.cwd(),"node_modules", "mls-agent-results", filename);
- return JSON.parse(fs.readFileSync(testDir).toString());
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tests/package-lock.json b/MLS.Agent.Tests/package-lock.json
deleted file mode 100644
index 182ebec91..000000000
--- a/MLS.Agent.Tests/package-lock.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "name": "mls-agent-results",
- "requires": true,
- "lockfileVersion": 1,
- "dependencies": {
- "@types/node": {
- "version": "10.12.12",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.12.tgz",
- "integrity": "sha512-Pr+6JRiKkfsFvmU/LK68oBRCQeEg36TyAbPhc2xpez24OOZZCuoIhWGTd39VZy6nGafSbxzGouFPTFD/rR1A0A=="
- }
- }
-}
diff --git a/MLS.Agent.Tests/package.json b/MLS.Agent.Tests/package.json
deleted file mode 100644
index 9571b55f8..000000000
--- a/MLS.Agent.Tests/package.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "name": "mls-agent-results",
- "description": "Package to verify if the agent and the simulator in the client are in sync",
- "main": "dist/index.js",
- "types": "dist/index.d.ts",
- "files": [
- "dist",
- "*.approved.json"
- ],
- "scripts": {
- "build": "tsc"
- },
- "repository": {
- "type": "git",
- "url": "https://msazure.visualstudio.com/DefaultCollection/One/_git/MLS-Agent"
- },
- "author": "MLS-Dev",
- "license": "ISC",
- "dependencies": {
- "@types/node": "^10.12.12"
- }
-}
diff --git a/MLS.Agent.Tests/tsconfig.json b/MLS.Agent.Tests/tsconfig.json
deleted file mode 100644
index 296e1afcc..000000000
--- a/MLS.Agent.Tests/tsconfig.json
+++ /dev/null
@@ -1,57 +0,0 @@
-{
- "compilerOptions": {
- /* Basic Options */
- "target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
- "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
- // "lib": [], /* Specify library files to be included in the compilation. */
- // "allowJs": true, /* Allow javascript files to be compiled. */
- // "checkJs": true, /* Report errors in .js files. */
- // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
- "declaration": true, /* Generates corresponding '.d.ts' file. */
- // "sourceMap": true, /* Generates corresponding '.map' file. */
- // "outFile": "./", /* Concatenate and emit output to single file. */
- "outDir": "dist", /* Redirect output structure to the directory. */
- // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
- // "removeComments": true, /* Do not emit comments to output. */
- // "noEmit": true, /* Do not emit outputs. */
- // "importHelpers": true, /* Import emit helpers from 'tslib'. */
- // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
- // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
-
- /* Strict Type-Checking Options */
- "strict": true, /* Enable all strict type-checking options. */
- // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
- // "strictNullChecks": true, /* Enable strict null checks. */
- // "strictFunctionTypes": true, /* Enable strict checking of function types. */
- // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
- // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
- // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
-
- /* Additional Checks */
- // "noUnusedLocals": true, /* Report errors on unused locals. */
- // "noUnusedParameters": true, /* Report errors on unused parameters. */
- // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
- // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
-
- /* Module Resolution Options */
- // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
- // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
- // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
- // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
- // "typeRoots": [], /* List of folders to include type definitions from. */
- "types": ["node"], /* Type declaration files to be included in compilation. */
- // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
- "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
- // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
-
- /* Source Map Options */
- // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
- // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
- // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
- // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
-
- /* Experimental Options */
- // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
- // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tools.Tests/DirectoryAccessorTests.cs b/MLS.Agent.Tools.Tests/DirectoryAccessorTests.cs
deleted file mode 100644
index 2bdd6d418..000000000
--- a/MLS.Agent.Tools.Tests/DirectoryAccessorTests.cs
+++ /dev/null
@@ -1,350 +0,0 @@
-// 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.IO;
-using System.Runtime.CompilerServices;
-using FluentAssertions;
-using Microsoft.DotNet.PlatformAbstractions;
-using MLS.Agent.Tools;
-using MLS.Agent.Tools.Tests;
-using Xunit;
-using static Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment;
-
-namespace MLS.Agent.Tests.Markdown
-{
- public abstract class DirectoryAccessorTests
- {
- public abstract IDirectoryAccessor GetDirectory(DirectoryInfo dirInfo, DirectoryInfo rootDirectoryToAddFiles = null);
-
- public abstract IDirectoryAccessor CreateDirectory([CallerMemberName]string testName = null);
-
- [Fact]
- public void It_can_retrieve_all_files_recursively()
- {
- var directory = GetDirectory(TestAssets.SampleConsole);
-
- var files = directory.GetAllFilesRecursively();
-
- files.Should()
- .Contain(new RelativeFilePath("BasicConsoleApp.csproj"))
- .And
- .Contain(new RelativeFilePath("Program.cs"))
- .And
- .Contain(new RelativeFilePath("Readme.md"))
- .And
- .Contain(new RelativeFilePath("Subdirectory/AnotherProgram.cs"))
- .And
- .Contain(new RelativeFilePath("Subdirectory/Tutorial.md"));
- }
-
- [Fact]
- public void It_can_retrieve_all_files_at_root()
- {
- var directory = GetDirectory(TestAssets.SampleConsole);
-
- var files = directory.GetAllFiles();
-
- files.Should()
- .Contain(new RelativeFilePath("BasicConsoleApp.csproj"))
- .And
- .Contain(new RelativeFilePath("Program.cs"))
- .And
- .Contain(new RelativeFilePath("Readme.md"))
- .And
- .NotContain(new RelativeFilePath("Subdirectory/AnotherProgram.cs"))
- .And
- .NotContain(new RelativeFilePath("Subdirectory/Tutorial.md"));
- }
-
- [Fact]
- public void GetAllFilesRecursively_does_not_return_directories()
- {
- var directory = GetDirectory(TestAssets.SampleConsole);
-
- var files = directory.GetAllFilesRecursively();
-
- files.Should().NotContain(f => f.Value.EndsWith("Subdirectory"));
- files.Should().NotContain(f => f.Value.EndsWith("Subdirectory/"));
- }
-
- [Fact]
- public void It_can_retrieve_all_directories_recursively()
- {
- var directory = GetDirectory(TestAssets.SampleConsole);
-
- var directories = directory.GetAllDirectoriesRecursively();
-
- directories.Should()
- .Contain(new RelativeDirectoryPath("Subdirectory"));
- }
-
- [Fact]
- public void GetAllDirectoriesRecursively_does_not_return_files()
- {
- var directory = GetDirectory(TestAssets.SampleConsole);
-
- var directories = directory.GetAllDirectoriesRecursively();
-
- directories.Should()
- .NotContain(d => d.Value.EndsWith("BasicConsoleApp.csproj"))
- .And
- .NotContain(d => d.Value.EndsWith("Program.cs"))
- .And
- .NotContain(d => d.Value.EndsWith("Readme.md"))
- .And
- .NotContain(d => d.Value.EndsWith("Subdirectory/AnotherProgram.cs"))
- .And
- .NotContain(d => d.Value.EndsWith("Subdirectory/Tutorial.md"));
- }
-
- [Theory]
- [InlineData(".")]
- [InlineData("./Subdirectory")]
- public void When_the_directory_exists_DirectoryExists_returns_true(string path)
- {
- var directoryAccessor = GetDirectory(TestAssets.SampleConsole);
-
- directoryAccessor.DirectoryExists(path).Should().BeTrue();
- }
-
- [Theory]
- [InlineData(".")]
- [InlineData("Subdirectory")]
- public void It_can_ensure_a_directory_exists(string path)
- {
- var directoryAccessor = CreateDirectory();
-
- directoryAccessor.EnsureDirectoryExists(path);
-
- directoryAccessor.DirectoryExists(path).Should().BeTrue();
- }
-
- [Fact]
- public void EnsureDirectoryExists_is_idempotent()
- {
- var directoryAccessor = CreateDirectory();
-
- var subdirectory = "./a-subdirectory";
-
- directoryAccessor.EnsureDirectoryExists(subdirectory);
-
- directoryAccessor
- .Invoking(d => d.EnsureDirectoryExists(subdirectory))
- .Should()
- .NotThrow();
- }
-
- [Theory]
- [InlineData("./some-file.txt", "hello!")]
- public void It_can_write_text_to_a_file(string path, string text)
- {
- var directory = CreateDirectory();
-
- directory.WriteAllText(path, text);
-
- directory.ReadAllText(path).Should().Be(text);
- }
-
- [Fact]
- public void It_can_overwrite_an_existing_file()
- {
- var directory = CreateDirectory();
-
- directory.WriteAllText("./some-file.txt", "original text");
- directory.WriteAllText("./some-file.txt", "updated text");
-
- directory.ReadAllText("./some-file.txt").Should().Be("updated text");
-
- }
-
- [Fact]
- public void When_the_file_exists_FileExists_returns_true()
- {
- var testDir = TestAssets.SampleConsole;
- GetDirectory(testDir).FileExists(new RelativeFilePath("Program.cs")).Should().BeTrue();
- }
-
- [Fact]
- public void When_the_filepath_is_null_FileExists_returns_false()
- {
- var testDir = TestAssets.SampleConsole;
- GetDirectory(testDir).Invoking(d => d.FileExists(null)).Should().Throw();
- }
-
- [Theory]
- [InlineData(@"Subdirectory/AnotherProgram.cs")]
- [InlineData(@"Subdirectory\AnotherProgram.cs")]
- public void When_the_filepath_contains_subdirectory_paths_FileExists_returns_true(string filepath)
- {
- var testDir = TestAssets.SampleConsole;
- GetDirectory(testDir).FileExists(new RelativeFilePath(filepath)).Should().BeTrue();
- }
-
- [Theory]
- [InlineData(@"../Program.cs")]
- [InlineData(@"..\Program.cs")]
- public void When_the_filepath_contains_a_path_that_looks_upward_in_tree_then_FileExists_returns_the_text(string filePath)
- {
- var rootDirectoryToAddFiles = TestAssets.SampleConsole;
- var testDir = new DirectoryInfo(Path.Combine(rootDirectoryToAddFiles.FullName, "Subdirectory"));
- GetDirectory(testDir, rootDirectoryToAddFiles).FileExists(new RelativeFilePath(filePath)).Should().BeTrue();
- }
-
- [Fact]
- public void When_the_filepath_contains_an_existing_file_ReadAllText_returns_the_text()
- {
- var testDir = TestAssets.SampleConsole;
- GetDirectory(testDir).ReadAllText(new RelativeFilePath("Program.cs")).Should().Contain("Hello World!");
- }
-
- [Theory]
- [InlineData(@"Subdirectory/AnotherProgram.cs")]
- [InlineData(@"Subdirectory\AnotherProgram.cs")]
- public void When_the_filepath_contains_an_existing_file_from_subdirectory_then_ReadAllText_returns_the_text(string filePath)
- {
- var testDir = TestAssets.SampleConsole;
- GetDirectory(testDir).ReadAllText(new RelativeFilePath(filePath)).Should().Contain("Hello from Another Program!");
- }
-
- [Theory]
- [InlineData(@"../Program.cs")]
- [InlineData(@"..\Program.cs")]
- public void When_the_filepath_contains_a_path_that_looks_upward_in_tree_then_ReadAllText_returns_the_text(string filePath)
- {
- var rootDirectoryToAddFiles = TestAssets.SampleConsole;
- var testDir = new DirectoryInfo(Path.Combine(rootDirectoryToAddFiles.FullName, "Subdirectory"));
- var value = GetDirectory(testDir, rootDirectoryToAddFiles).ReadAllText(new RelativeFilePath(filePath));
- value.Should().Contain("Hello World!");
- }
-
- [Fact]
- public void Should_return_a_directory_accessor_for_a_relative_path()
- {
- var rootDir = TestAssets.SampleConsole;
- var outerDirAccessor = GetDirectory(rootDir);
- var inner = outerDirAccessor.GetDirectoryAccessorForRelativePath(new RelativeDirectoryPath("Subdirectory"));
- inner.FileExists(new RelativeFilePath("AnotherProgram.cs")).Should().BeTrue();
- }
-
- [Fact]
- public void Path_separators_are_uniform()
- {
- var directory = GetDirectory(TestAssets.SampleConsole);
- var unexpectedPathSeparator = OperatingSystemPlatform == Platform.Windows
- ? "/"
- : "\\";
-
- foreach (var relativePath in directory.GetAllFilesRecursively())
- {
- var fullyQualifiedPath = directory.GetFullyQualifiedPath(relativePath).FullName;
- fullyQualifiedPath.Should().NotContain(unexpectedPathSeparator);
- }
- }
-
- [Fact]
- public void It_can_make_a_directory_accessor_from_an_absolute_DirectoryInfo()
- {
-
- var directory = GetDirectory(TestAssets.SampleConsole);
-
- var fullyQualifiedSubdirectory = new DirectoryInfo(directory.GetFullyQualifiedFilePath("./Subdirectory/").FullName);
-
- var subdirectory = directory.GetDirectoryAccessorFor(fullyQualifiedSubdirectory);
-
- subdirectory.FileExists("Tutorial.md").Should().BeTrue();
- }
- }
-
- public class FileSystemDirectoryAccessorTests : DirectoryAccessorTests
- {
- public override IDirectoryAccessor CreateDirectory([CallerMemberName]string testName = null)
- {
- var directory = PackageUtilities.CreateDirectory(testName);
-
- return new FileSystemDirectoryAccessor(directory);
- }
-
- public override IDirectoryAccessor GetDirectory(DirectoryInfo directoryInfo, DirectoryInfo rootDirectoryToAddFiles = null)
- {
- return new FileSystemDirectoryAccessor(directoryInfo);
- }
- }
-
- public class InMemoryDirectoryAccessorTests : DirectoryAccessorTests
- {
- public override IDirectoryAccessor CreateDirectory([CallerMemberName]string testName = null)
- {
- return new InMemoryDirectoryAccessor();
- }
-
- [Theory]
- [InlineData("one")]
- [InlineData("./one")]
- [InlineData("./one/two")]
- [InlineData("./one/two/three")]
- public void DirectoryExists_returns_true_for_parent_directories_of_explicitly_added_relative_file_paths(string relativeDirectoryPath)
- {
- var directory = new InMemoryDirectoryAccessor
- {
- ("./one/two/three/file.txt", "")
- };
-
- directory.DirectoryExists(relativeDirectoryPath).Should().BeTrue();
- }
-
- public override IDirectoryAccessor GetDirectory(DirectoryInfo rootDirectory, DirectoryInfo rootDirectoryToAddFiles = null)
- {
- return new InMemoryDirectoryAccessor(rootDirectory, rootDirectoryToAddFiles)
- {
- ("BasicConsoleApp.csproj",
-@"
-
-
- Exe
- netcoreapp2.1
-
-
-
-"),
- ("Program.cs",
-@"using System;
-
-namespace BasicConsoleApp
-{
- class Program
- {
- static void MyProgram(string[] args)
- {
- Console.WriteLine(""Hello World!"");
- }
- }
-}"),
- ("Readme.md",
-@"This is a sample *markdown file*
-
-```cs Program.cs
-```"),
- ("./Subdirectory/Tutorial.md", "This is a sample *tutorial file*"),
- ("./Subdirectory/AnotherProgram.cs",
-@"using System;
-using System.Collections.Generic;
-using System.Text;
-
-namespace MLS.Agent.Tests.TestProjects.BasicConsoleApp.Subdirectory
-{
- class AnotherPorgram
- {
- static void MyAnotherProgram(string[] args)
- {
- Console.WriteLine(""Hello from Another Program!"");
- }
- }
- }
-")
- };
- }
- }
-}
-
-
diff --git a/MLS.Agent.Tools.Tests/InMemoryDirectoryAccessor.cs b/MLS.Agent.Tools.Tests/InMemoryDirectoryAccessor.cs
deleted file mode 100644
index 36571fb49..000000000
--- a/MLS.Agent.Tools.Tests/InMemoryDirectoryAccessor.cs
+++ /dev/null
@@ -1,209 +0,0 @@
-// 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;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-
-namespace MLS.Agent.Tools.Tests
-{
- public class InMemoryDirectoryAccessor : IDirectoryAccessor, IEnumerable
- {
- private readonly DirectoryInfo _rootDirToAddFiles;
-
- private Dictionary _files = new Dictionary(
- new Dictionary(),
- new FileSystemInfoComparer());
-
- public InMemoryDirectoryAccessor(
- DirectoryInfo workingDirectory = null,
- DirectoryInfo rootDirectoryToAddFiles = null)
- {
- WorkingDirectory = workingDirectory ??
- new DirectoryInfo(Path.Combine("some", "fake", "path"));
-
- _rootDirToAddFiles = rootDirectoryToAddFiles ??
- WorkingDirectory;
- }
-
- internal DirectoryInfo WorkingDirectory { get; }
-
- public void Add((string path, string content) file)
- {
- var fileInfo = new FileInfo(Path.Combine(_rootDirToAddFiles.FullName, file.path));
-
- _files.Add(fileInfo, file.content);
-
- var directory = fileInfo.Directory;
-
- while (directory != null &&
- !FileSystemInfoComparer.Instance.Equals(directory, WorkingDirectory))
- {
- _files.TryAdd(directory, null);
-
- directory = directory.Parent;
- }
- }
-
- public FileSystemDirectoryAccessor CreateFiles()
- {
- foreach (var filePath in GetAllFilesRecursively())
- {
- var absolutePath = GetFullyQualifiedPath(filePath);
-
- var text = ReadAllText(filePath);
-
- if (absolutePath is FileInfo file)
- {
- if (!file.Directory.Exists)
- {
- file.Directory.Create();
- }
-
- File.WriteAllText(absolutePath.FullName, text);
- }
- }
-
- return new FileSystemDirectoryAccessor(WorkingDirectory);
- }
-
- public bool DirectoryExists(RelativeDirectoryPath path)
- {
- var fullyQualifiedDirPath = GetFullyQualifiedPath(path);
-
- return _files
- .Keys
- .Any(f =>
- {
- switch (f)
- {
- case FileInfo file:
- return FileSystemInfoComparer.Instance.Equals(
- file.Directory,
- fullyQualifiedDirPath);
-
- case DirectoryInfo dir:
- return FileSystemInfoComparer.Instance.Equals(
- dir,
- fullyQualifiedDirPath);
-
- default:
- throw new NotSupportedException();
- }
- });
- }
-
- public void EnsureDirectoryExists(RelativeDirectoryPath path)
- {
- _files[GetFullyQualifiedPath(path)] = null;
- }
-
- public bool FileExists(RelativeFilePath path)
- {
- return _files.ContainsKey(GetFullyQualifiedPath(path));
- }
-
- public string ReadAllText(RelativeFilePath path)
- {
- _files.TryGetValue(GetFullyQualifiedPath(path), out var value);
- return value;
- }
-
- public void WriteAllText(RelativeFilePath path, string text)
- {
- _files[GetFullyQualifiedPath(path)] = text;
- }
-
- public FileSystemInfo GetFullyQualifiedPath(RelativePath path)
- {
- if (path == null)
- {
- throw new ArgumentNullException();
- }
-
- switch (path)
- {
- case RelativeFilePath rfp:
- return WorkingDirectory.Combine(rfp);
- case RelativeDirectoryPath rdp:
- return WorkingDirectory.Combine(rdp);
- default:
- throw new NotSupportedException();
- }
- }
-
- public IEnumerator GetEnumerator()
- {
- throw new NotImplementedException();
- }
-
- public IDirectoryAccessor GetDirectoryAccessorForRelativePath(RelativeDirectoryPath relativePath)
- {
- var newPath = WorkingDirectory.Combine(relativePath);
- return new InMemoryDirectoryAccessor(newPath)
- {
- _files = _files
- };
- }
-
- public IEnumerable GetAllDirectoriesRecursively()
- {
- return _files.Keys
- .OfType()
- .Select(key => new RelativeDirectoryPath(
- Path.GetRelativePath(WorkingDirectory.FullName, key.FullName)));
- }
-
- public IEnumerable GetAllFiles()
- {
- return _files.Keys
- .OfType()
- .Where(key => FileSystemInfoComparer.Instance.Equals(key.Directory, WorkingDirectory))
- .Select(key => new RelativeFilePath(
- Path.GetRelativePath(WorkingDirectory.FullName, key.FullName)));
- }
-
- public IEnumerable GetAllFilesRecursively()
- {
- return _files.Keys
- .OfType()
- .Select(key => new RelativeFilePath(
- Path.GetRelativePath(WorkingDirectory.FullName, key.FullName)));
- }
-
- public override string ToString() => this.GetFullyQualifiedRoot().FullName;
-
- private class FileSystemInfoComparer : IEqualityComparer
- {
- public static FileSystemInfoComparer Instance { get; } = new FileSystemInfoComparer();
-
- public bool Equals(FileSystemInfo x, FileSystemInfo y)
- {
- if (x?.GetType() == y?.GetType() && x != null)
- {
- return x is DirectoryInfo
- ? RelativePath.NormalizeDirectory(x.FullName) == RelativePath.NormalizeDirectory(y.FullName)
- : x.FullName == y.FullName;
- }
-
- return false;
- }
-
- public int GetHashCode(FileSystemInfo obj)
- {
- var fullName = obj.FullName;
-
- if (obj is DirectoryInfo)
- {
- fullName = RelativePath.NormalizeDirectory(fullName);
- }
-
- var hashCode = $"{obj.GetType().GetHashCode()}:{fullName}".GetHashCode();
-
- return hashCode;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tools.Tests/MLS.Agent.Tools.Tests.csproj b/MLS.Agent.Tools.Tests/MLS.Agent.Tools.Tests.csproj
deleted file mode 100644
index 7f4021daf..000000000
--- a/MLS.Agent.Tools.Tests/MLS.Agent.Tools.Tests.csproj
+++ /dev/null
@@ -1,48 +0,0 @@
-
-
-
- net6.0
- Latest
- portable-net45+win8+wp8+wpa81
- $(NoWarn);8002
-
-
-
-
-
-
-
-
-
-
-
- Always
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
-
diff --git a/MLS.Agent.Tools.Tests/PackageUtilities.cs b/MLS.Agent.Tools.Tests/PackageUtilities.cs
deleted file mode 100644
index 6de7f7577..000000000
--- a/MLS.Agent.Tools.Tests/PackageUtilities.cs
+++ /dev/null
@@ -1,90 +0,0 @@
-// 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.IO;
-using System.Reactive.Concurrency;
-using System.Threading.Tasks;
-using Clockwise;
-using WorkspaceServer.Packaging;
-
-namespace MLS.Agent.Tools.Tests
-{
- public static class PackageUtilities
- {
- private static readonly object CreateDirectoryLock = new object();
-
- public static async Task Copy(
- Package fromPackage,
- string folderNameStartsWith = null,
- bool isRebuildable = false,
- IScheduler buildThrottleScheduler = null,
- DirectoryInfo parentDirectory = null)
- {
- if (fromPackage == null)
- {
- throw new ArgumentNullException(nameof(fromPackage));
- }
-
- await fromPackage.EnsureReady(new Budget());
-
- folderNameStartsWith = folderNameStartsWith ?? fromPackage.Name;
- parentDirectory = parentDirectory ?? fromPackage.Directory.Parent;
-
- var destination =
- CreateDirectory(folderNameStartsWith,
- parentDirectory);
-
- fromPackage.Directory.CopyTo(destination, info =>
- {
- switch (info)
- {
- case FileInfo fileInfo:
- return FileLock.IsLockFile(fileInfo) || fileInfo.Extension.EndsWith("binlog");
- default:
- return false;
- }
- });
-
- Package copy;
- if (isRebuildable)
- {
- copy = new RebuildablePackage(directory: destination, name: destination.Name, buildThrottleScheduler: buildThrottleScheduler);
- }
- else
- {
- copy = new NonrebuildablePackage(directory: destination, name: destination.Name, buildThrottleScheduler: buildThrottleScheduler);
- }
-
- return copy;
- }
-
- public static DirectoryInfo CreateDirectory(
- string folderNameStartsWith,
- DirectoryInfo parentDirectory = null)
- {
- if (string.IsNullOrWhiteSpace(folderNameStartsWith))
- {
- throw new ArgumentException("Value cannot be null or whitespace.", nameof(folderNameStartsWith));
- }
-
- parentDirectory = parentDirectory ?? Package.DefaultPackagesDirectory;
-
- DirectoryInfo created;
-
- lock (CreateDirectoryLock)
- {
- if (!parentDirectory.Exists)
- {
- parentDirectory.Create();
- }
-
- var existingFolders = parentDirectory.GetDirectories($"{folderNameStartsWith}.*");
-
- created = parentDirectory.CreateSubdirectory($"{folderNameStartsWith}.{existingFolders.Length + 1}");
- }
-
- return created;
- }
- }
-}
diff --git a/MLS.Agent.Tools.Tests/RelativeDirectoryPathTests.cs b/MLS.Agent.Tools.Tests/RelativeDirectoryPathTests.cs
deleted file mode 100644
index b6515ce5f..000000000
--- a/MLS.Agent.Tools.Tests/RelativeDirectoryPathTests.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-// 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 FluentAssertions;
-using Xunit;
-
-namespace MLS.Agent.Tools.Tests
-{
- public class RelativeDirectoryPathTests
- {
- [Fact]
- public void Can_create_directory_paths_from_string_with_directory()
- {
- var path = new RelativeDirectoryPath("../src");
- path.Value.Should().Be("../src/");
- }
-
- [Fact]
- public void Normalises_the_passed_path()
- {
- var path = new RelativeDirectoryPath(@"..\src");
- path.Value.Should().Be("../src/");
- }
-
- [Fact]
- public void Throws_exception_if_the_path_contains_invalid_path_characters()
- {
- Action action = () => new RelativeDirectoryPath(@"abc|def");
- action.Should().Throw();
- }
-
- [Theory]
- [InlineData("/")]
- [InlineData("/some/path")]
- [InlineData(@"c:\some\path")]
- [InlineData(@"\\some\path")]
- public void Throws_if_path_is_absolute(string value)
- {
- Action action = () => new RelativeDirectoryPath(value);
- action.Should().Throw();
- }
-
- [Theory]
- [InlineData(".", ".")]
- [InlineData(".", "./")]
- [InlineData(".", @".\")]
- [InlineData("./", @".\")]
- [InlineData("..", "..")]
- [InlineData(@"../", @"..\")]
- [InlineData("../a/", "../a")]
- [InlineData("a", "./a")]
- public void Equality_is_based_on_same_resolved_directory_path(
- string value1,
- string value2)
- {
- var path1 = new RelativeDirectoryPath(value1);
- var path2 = new RelativeDirectoryPath(value2);
-
- path1.GetHashCode().Should().Be(path2.GetHashCode());
- path1.Equals(path2).Should().BeTrue();
- path2.Equals(path1).Should().BeTrue();
- }
- }
-}
diff --git a/MLS.Agent.Tools.Tests/RelativeFilePathTests.cs b/MLS.Agent.Tools.Tests/RelativeFilePathTests.cs
deleted file mode 100644
index be0b2854e..000000000
--- a/MLS.Agent.Tools.Tests/RelativeFilePathTests.cs
+++ /dev/null
@@ -1,103 +0,0 @@
-// 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 FluentAssertions;
-using MLS.Agent.Tools;
-using Xunit;
-using Xunit.Abstractions;
-
-namespace MLS.Agent.Tools.Tests
-{
- public class RelativeFilePathTests
- {
- private readonly ITestOutputHelper _output;
-
- public RelativeFilePathTests(ITestOutputHelper output)
- {
- _output = output;
- }
-
- [Fact]
- public void Can_create_file_paths_from_string_with_directory()
- {
- var path = new RelativeFilePath("../readme.md");
- path.Value.Should().Be("../readme.md");
- }
-
- [Fact]
- public void Can_create_file_paths_from_string_without_directory()
- {
- var path = new RelativeFilePath("readme.md");
- path.Value.Should().Be("./readme.md");
- }
-
- [Fact]
- public void Normalises_the_passed_path()
- {
- var path = new RelativeFilePath(@"..\readme.md");
- _output.WriteLine(path.Value);
- _output.WriteLine(path.Directory.Value);
- path.Value.Should().Be("../readme.md");
- }
-
- [Fact]
- public void Throws_exception_if_the_path_contains_invalid_filename_characters()
- {
- Action action = () => new RelativeFilePath(@"abc*def");
- action.Should().Throw();
- }
-
- [Fact]
- public void Throws_exception_if_the_path_contains_invalid_path_characters()
- {
- Action action = () => new RelativeFilePath(@"abc|def");
- action.Should().Throw();
- }
-
- [Fact]
- public void Throws_exception_if_the_path_is_empty()
- {
- Action action = () => new RelativeFilePath("");
- action.Should().Throw();
- }
-
- [Theory]
- [InlineData("../src/Program.cs", "../src/")]
- [InlineData("src/Program.cs", "./src/")]
- [InlineData("Readme.md", "./")]
- public void Returns_the_directory_path(string path, string directory)
- {
- var relativePath = new RelativeFilePath(path);
- relativePath.Directory.Value.Should().Be(directory);
- }
-
- [Fact]
- public void Extension_returns_file_extension_with_a_dot()
- {
- new RelativeFilePath("../Program.cs").Extension.Should().Be(".cs");
- }
-
- [Theory]
- [InlineData("Program.cs", "Program.cs")]
- [InlineData("./Program.cs", "Program.cs")]
- [InlineData("./Program.cs", @".\Program.cs")]
- [InlineData("./a/Program.cs", @".\a/Program.cs")]
- public void Equality_is_based_on_same_resolved_file_path(
- string value1,
- string value2)
- {
- var path1 = new RelativeFilePath(value1);
- var path2 = new RelativeFilePath(value2);
-
- _output.WriteLine($"path1.Value: {path1.Value}");
- _output.WriteLine($"path1.Directory.Value: {path1.Directory.Value}");
- _output.WriteLine($"path2.Value: {path2.Value}");
- _output.WriteLine($"path2.Directory.Value: {path2.Directory.Value}");
-
- path1.GetHashCode().Should().Be(path2.GetHashCode());
- path1.Equals(path2).Should().BeTrue();
- path2.Equals(path1).Should().BeTrue();
- }
- }
-}
diff --git a/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/BasicConsoleApp.csproj b/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/BasicConsoleApp.csproj
deleted file mode 100644
index c73e0d169..000000000
--- a/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/BasicConsoleApp.csproj
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
- Exe
- netcoreapp3.1
-
-
-
diff --git a/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Program.cs b/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Program.cs
deleted file mode 100644
index 9747aab5b..000000000
--- a/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Program.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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;
-
-namespace BasicConsoleApp
-{
- class Program
- {
- static void Main()
- {
- #region theregion
- Console.WriteLine("Hello World!");
- #endregion
- }
- }
-}
diff --git a/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Readme.md b/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Readme.md
deleted file mode 100644
index 0a2754628..000000000
--- a/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Readme.md
+++ /dev/null
@@ -1,4 +0,0 @@
-This is a sample *markdown file*
-
-```cs --source-file Program.cs
-```
\ No newline at end of file
diff --git a/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Subdirectory/AnotherProgram.cs b/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Subdirectory/AnotherProgram.cs
deleted file mode 100644
index c99dfa178..000000000
--- a/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Subdirectory/AnotherProgram.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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.Text;
-
-namespace MLS.Agent.Tests.TestProjects.BasicConsoleApp.Subdirectory
-{
- class AnotherPorgram
- {
- static void MyAnotherProgram(string[] args)
- {
- Console.WriteLine("Hello from Another Program!");
- }
- }
-}
diff --git a/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Subdirectory/Tutorial.md b/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Subdirectory/Tutorial.md
deleted file mode 100644
index 161c19a39..000000000
--- a/MLS.Agent.Tools.Tests/TestProjects/SampleConsole/Subdirectory/Tutorial.md
+++ /dev/null
@@ -1 +0,0 @@
-This is a sample *tutorial file*
\ No newline at end of file
diff --git a/MLS.Agent.Tools.Tests/TestUtility/TestAssets.cs b/MLS.Agent.Tools.Tests/TestUtility/TestAssets.cs
deleted file mode 100644
index 8c84cd6eb..000000000
--- a/MLS.Agent.Tools.Tests/TestUtility/TestAssets.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// 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.IO;
-
-namespace MLS.Agent.Tools.Tests
-{
- public static class TestAssets
- {
- public static DirectoryInfo SampleConsole =>
- new DirectoryInfo(Path.Combine(GetTestProjectsFolder(), "SampleConsole"));
-
- public static DirectoryInfo KernelExtension =>
- new DirectoryInfo(Path.Combine(GetTestProjectsFolder(), "KernelExtension"));
-
- private static string GetTestProjectsFolder()
- {
- var current = Directory.GetCurrentDirectory();
- return Path.Combine(current, "TestProjects");
- }
- }
-}
diff --git a/MLS.Agent.Tools/AsyncLazy{T}.cs b/MLS.Agent.Tools/AsyncLazy{T}.cs
deleted file mode 100644
index 3305aa446..000000000
--- a/MLS.Agent.Tools/AsyncLazy{T}.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-// 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;
-
-namespace MLS.Agent.Tools
-{
- public class AsyncLazy
- {
- private readonly Lazy> _lazy;
-
- public AsyncLazy(Func> initialize)
- {
- if (initialize == null)
- {
- throw new ArgumentNullException(nameof(initialize));
- }
-
- _lazy = new Lazy>(initialize);
- }
-
- public Task ValueAsync() => _lazy.Value;
- }
-}
diff --git a/MLS.Agent.Tools/DirectoryAccessor.cs b/MLS.Agent.Tools/DirectoryAccessor.cs
deleted file mode 100644
index f373ab242..000000000
--- a/MLS.Agent.Tools/DirectoryAccessor.cs
+++ /dev/null
@@ -1,72 +0,0 @@
-// 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.IO;
-using Microsoft.DotNet.Interactive.Utility;
-
-namespace MLS.Agent.Tools
-{
- public static class DirectoryAccessor
- {
- public static bool DirectoryExists(
- this IDirectoryAccessor directoryAccessor,
- string relativePath) =>
- directoryAccessor.DirectoryExists(new RelativeDirectoryPath(relativePath));
-
- public static bool RootDirectoryExists(
- this IDirectoryAccessor directoryAccessor) =>
- directoryAccessor.DirectoryExists(new RelativeDirectoryPath("."));
-
- public static void EnsureDirectoryExists(
- this IDirectoryAccessor directoryAccessor,
- string relativePath) =>
- directoryAccessor.EnsureDirectoryExists(new RelativeDirectoryPath(relativePath));
-
- public static void EnsureRootDirectoryExists(
- this IDirectoryAccessor directoryAccessor) =>
- directoryAccessor.EnsureDirectoryExists(new RelativeDirectoryPath("."));
-
- public static bool FileExists(
- this IDirectoryAccessor directoryAccessor,
- string relativePath) =>
- directoryAccessor.FileExists(new RelativeFilePath(relativePath));
-
- public static string ReadAllText(
- this IDirectoryAccessor directoryAccessor,
- string relativePath) =>
- directoryAccessor.ReadAllText(new RelativeFilePath(relativePath));
-
- public static void WriteAllText(
- this IDirectoryAccessor directoryAccessor,
- string relativePath,
- string text) =>
- directoryAccessor.WriteAllText(
- new RelativeFilePath(relativePath),
- text);
-
- public static IDirectoryAccessor GetDirectoryAccessorForRelativePath(
- this IDirectoryAccessor directoryAccessor,
- string relativePath) =>
- directoryAccessor.GetDirectoryAccessorForRelativePath(new RelativeDirectoryPath(relativePath));
-
- public static IDirectoryAccessor GetDirectoryAccessorFor(this IDirectoryAccessor directory, DirectoryInfo directoryInfo)
- {
- var relative = PathUtilities.GetRelativePath(
- directory.GetFullyQualifiedRoot().FullName,
- directoryInfo.FullName);
- return directory.GetDirectoryAccessorForRelativePath(new RelativeDirectoryPath(relative));
- }
-
- public static DirectoryInfo GetFullyQualifiedRoot(this IDirectoryAccessor directoryAccessor) =>
- (DirectoryInfo) directoryAccessor.GetFullyQualifiedPath(new RelativeDirectoryPath("."));
-
- public static FileInfo GetFullyQualifiedFilePath(this IDirectoryAccessor directoryAccessor, string relativeFilePath) =>
- GetFullyQualifiedFilePath(directoryAccessor, new RelativeFilePath(relativeFilePath));
-
- public static FileInfo GetFullyQualifiedFilePath(this IDirectoryAccessor directoryAccessor, RelativeFilePath relativePath) =>
- (FileInfo) directoryAccessor.GetFullyQualifiedPath(relativePath);
-
- public static DirectoryInfo GetFullyQualifiedDirectoryPath(this IDirectoryAccessor directoryAccessor, RelativeDirectoryPath relativePath) =>
- (DirectoryInfo)directoryAccessor.GetFullyQualifiedPath(relativePath);
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tools/DirectoryInfoExtensions.cs b/MLS.Agent.Tools/DirectoryInfoExtensions.cs
deleted file mode 100644
index ddac8b140..000000000
--- a/MLS.Agent.Tools/DirectoryInfoExtensions.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-// 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.IO;
-
-namespace MLS.Agent.Tools
-{
- public static class DirectoryInfoExtensions
- {
- public static void CopyTo(
- this DirectoryInfo source,
- DirectoryInfo destination,
- Func skipWhen = null)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- if (!source.Exists)
- {
- throw new DirectoryNotFoundException(source.FullName);
- }
-
- if (!destination.Exists)
- {
- destination.Create();
- }
-
- foreach (var file in source.GetFiles())
- {
- if (skipWhen?.Invoke(file) == true)
- {
- continue;
- }
-
- file.CopyTo(
- Path.Combine(
- destination.FullName, file.Name), false);
- }
-
- foreach (var subdirectory in source.GetDirectories())
- {
- if (skipWhen?.Invoke(subdirectory) == true)
- {
- continue;
- }
-
- subdirectory.CopyTo(
- new DirectoryInfo(
- Path.Combine(
- destination.FullName, subdirectory.Name)));
- }
- }
-
- public static DirectoryInfo Subdirectory(this DirectoryInfo directoryInfo, string path)
- {
- return new DirectoryInfo(Path.Combine(directoryInfo.FullName, path));
- }
-
- public static FileInfo File(this DirectoryInfo directoryInfo, string name)
- {
- return new FileInfo(Path.Combine(directoryInfo.FullName, name));
- }
-
- public static DirectoryInfo NormalizeEnding(this DirectoryInfo directoryInfo)
- {
- if (!directoryInfo.FullName.EndsWith(Path.DirectorySeparatorChar.ToString()))
- {
- return new DirectoryInfo(Path.Combine(directoryInfo.FullName, Path.DirectorySeparatorChar.ToString()));
- }
-
- return directoryInfo;
- }
- }
-}
diff --git a/MLS.Agent.Tools/FileInfoExtensions.cs b/MLS.Agent.Tools/FileInfoExtensions.cs
deleted file mode 100644
index 3ac4f88dd..000000000
--- a/MLS.Agent.Tools/FileInfoExtensions.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-// 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.IO;
-using System.Threading.Tasks;
-
-namespace MLS.Agent.Tools
-{
- public static class FileInfoExtensions
- {
- public static string Read(this FileInfo file)
- {
- using (var reader = file.OpenText())
- {
- return reader.ReadToEnd();
- }
- }
-
- public static async Task ReadAsync(this FileInfo file)
- {
- using (var reader = file.OpenText())
- {
- return await reader.ReadToEndAsync();
- }
- }
-
- public static bool IsBuildOutput(this FileInfo fileInfo)
- {
- var directory = fileInfo.Directory;
-
- while (directory != null)
- {
- if (directory.Name == "obj" || directory.Name == "bin")
- {
- return true;
- }
-
- directory = directory.Parent;
- }
-
- return false;
- }
- }
-}
diff --git a/MLS.Agent.Tools/FileSystemDirectoryAccessor.cs b/MLS.Agent.Tools/FileSystemDirectoryAccessor.cs
deleted file mode 100644
index b5c6d8a31..000000000
--- a/MLS.Agent.Tools/FileSystemDirectoryAccessor.cs
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright (c) .NET Foundation and contributors. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using Microsoft.DotNet.Interactive.Utility;
-
-namespace MLS.Agent.Tools
-{
- public class FileSystemDirectoryAccessor : IDirectoryAccessor
- {
- private readonly DirectoryInfo _rootDirectory;
-
- public FileSystemDirectoryAccessor(string directory): this(new DirectoryInfo(directory))
- {
- }
-
- public FileSystemDirectoryAccessor(DirectoryInfo rootDir)
- {
- _rootDirectory = rootDir ?? throw new ArgumentNullException(nameof(rootDir));
- }
-
- public bool DirectoryExists(RelativeDirectoryPath path)
- {
- return GetFullyQualifiedPath(path).Exists;
- }
-
- public bool FileExists(RelativeFilePath filePath)
- {
- return GetFullyQualifiedPath(filePath).Exists;
- }
-
- public void EnsureDirectoryExists(RelativeDirectoryPath path)
- {
- var fullyQualifiedPath = GetFullyQualifiedPath(path);
-
- if (!Directory.Exists(fullyQualifiedPath.FullName))
- {
- Directory.CreateDirectory(fullyQualifiedPath.FullName);
- }
- }
-
- public string ReadAllText(RelativeFilePath filePath)
- {
- return File.ReadAllText(GetFullyQualifiedPath(filePath).FullName);
- }
-
- public void WriteAllText(RelativeFilePath path, string text)
- {
- File.WriteAllText(GetFullyQualifiedPath(path).FullName, text);
- }
-
- public FileSystemInfo GetFullyQualifiedPath(RelativePath path)
- {
- if (path == null)
- {
- throw new ArgumentNullException(nameof(path));
- }
-
- return path.Match(
- directory => new DirectoryInfo(_rootDirectory.Combine(directory).FullName),
- file => new FileInfo(_rootDirectory.Combine(file).FullName)
- );
- }
-
- public IDirectoryAccessor GetDirectoryAccessorForRelativePath(RelativeDirectoryPath relativePath)
- {
- var absolutePath = _rootDirectory.Combine(relativePath).FullName;
- return new FileSystemDirectoryAccessor(new DirectoryInfo(absolutePath));
- }
-
-
- public IEnumerable GetAllDirectoriesRecursively()
- {
- var directories = _rootDirectory.GetDirectories("*", SearchOption.AllDirectories);
-
- return directories.Select(f =>
- new RelativeDirectoryPath(PathUtilities.GetRelativePath(_rootDirectory.FullName, f.FullName)));
- }
-
- public IEnumerable GetAllFilesRecursively()
- {
- var files = _rootDirectory.GetFiles("*", SearchOption.AllDirectories);
-
- return files.Select(f =>
- new RelativeFilePath(PathUtilities.GetRelativePath(_rootDirectory.FullName, f.FullName)));
- }
-
- public IEnumerable GetAllFiles()
- {
- var files = _rootDirectory.GetFiles("*", SearchOption.TopDirectoryOnly);
-
- return files.Select(f =>
- new RelativeFilePath(PathUtilities.GetRelativePath(_rootDirectory.FullName, f.FullName)));
- }
-
- public override string ToString() => _rootDirectory.FullName;
- }
-}
diff --git a/MLS.Agent.Tools/IDirectoryAccessor.cs b/MLS.Agent.Tools/IDirectoryAccessor.cs
deleted file mode 100644
index 3ffbe3652..000000000
--- a/MLS.Agent.Tools/IDirectoryAccessor.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-// 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.Generic;
-using System.IO;
-
-namespace MLS.Agent.Tools
-{
- public interface IDirectoryAccessor
- {
- bool FileExists(RelativeFilePath path);
-
- bool DirectoryExists(RelativeDirectoryPath path);
-
- void EnsureDirectoryExists(RelativeDirectoryPath path);
-
- string ReadAllText(RelativeFilePath path);
-
- void WriteAllText(RelativeFilePath path, string text);
-
- IEnumerable GetAllFilesRecursively();
-
- IEnumerable GetAllFiles();
-
- IEnumerable GetAllDirectoriesRecursively();
-
- FileSystemInfo GetFullyQualifiedPath(RelativePath path);
-
- IDirectoryAccessor GetDirectoryAccessorForRelativePath(RelativeDirectoryPath path);
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tools/MLS.Agent.Tools.csproj b/MLS.Agent.Tools/MLS.Agent.Tools.csproj
deleted file mode 100644
index 63a576fd4..000000000
--- a/MLS.Agent.Tools/MLS.Agent.Tools.csproj
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-
- netstandard2.0
- Latest
- $(NoWarn);8002
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- all
-
-
-
-
-
-
-
-
diff --git a/MLS.Agent.Tools/RelativeDirectoryPath.cs b/MLS.Agent.Tools/RelativeDirectoryPath.cs
deleted file mode 100644
index a31adf63f..000000000
--- a/MLS.Agent.Tools/RelativeDirectoryPath.cs
+++ /dev/null
@@ -1,66 +0,0 @@
-// 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;
-
-namespace MLS.Agent.Tools
-{
- public class RelativeDirectoryPath :
- RelativePath,
- IEquatable
- {
- public static RelativeDirectoryPath Root { get; } = new RelativeDirectoryPath("./");
-
- public RelativeDirectoryPath(string value) : base(value)
- {
- Value = NormalizeDirectory(value);
- }
-
- public bool Equals(RelativeDirectoryPath other)
- {
- if (ReferenceEquals(null, other))
- {
- return false;
- }
-
- if (ReferenceEquals(this, other))
- {
- return true;
- }
-
- return Equals(Value, other.Value);
- }
-
- public override bool Equals(object obj)
- {
- if (ReferenceEquals(null, obj))
- {
- return false;
- }
-
- if (ReferenceEquals(this, obj))
- {
- return true;
- }
-
- if (obj.GetType() != GetType())
- {
- return false;
- }
-
- return Equals((RelativeDirectoryPath) obj);
- }
-
- public override int GetHashCode() => Value.GetHashCode();
-
- public static bool operator ==(RelativeDirectoryPath left, RelativeDirectoryPath right)
- {
- return Equals(left, right);
- }
-
- public static bool operator !=(RelativeDirectoryPath left, RelativeDirectoryPath right)
- {
- return !Equals(left, right);
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tools/RelativeFilePath.cs b/MLS.Agent.Tools/RelativeFilePath.cs
deleted file mode 100644
index d07a2cb64..000000000
--- a/MLS.Agent.Tools/RelativeFilePath.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-// 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.IO;
-
-namespace MLS.Agent.Tools
-{
- public class RelativeFilePath :
- RelativePath,
- IEquatable
- {
- public RelativeFilePath(string value) : base(value)
- {
- if (string.IsNullOrWhiteSpace(value))
- {
- throw new ArgumentException("File path cannot be null or consist entirely of whitespace", nameof(value));
- }
-
- var (directoryPath, fileName) = GetFileAndDirectoryNames(value);
-
- FileName = fileName;
-
- ThrowIfContainsDisallowedFilePathChars(FileName);
-
- Directory = new RelativeDirectoryPath(directoryPath);
-
- Value = Directory.Value + FileName;
- }
-
- private static (string directoryPath, string fileName) GetFileAndDirectoryNames(string filePath)
- {
- var lastDirectorySeparatorPos = filePath.LastIndexOfAny(new[] { '\\', '/' });
-
- if (lastDirectorySeparatorPos == -1)
- {
- return ("./", filePath);
- }
-
- var fileName = filePath.Substring(lastDirectorySeparatorPos + 1);
-
- var directoryPath = filePath.Substring(0, lastDirectorySeparatorPos);
-
- directoryPath = NormalizeDirectory(directoryPath);
-
- return (directoryPath, fileName);
- }
-
- public string FileName { get; }
-
- public RelativeDirectoryPath Directory { get; }
-
- public string Extension =>
- Path.GetExtension(Value);
-
- public static bool TryParse(string path, out RelativeFilePath relativeFilePath)
- {
- relativeFilePath = null;
- try
- {
- relativeFilePath = new RelativeFilePath(path);
- return true;
- }
- catch
- {
- return false;
- }
- }
-
- public bool Equals(RelativeFilePath other)
- {
- if (ReferenceEquals(null, other))
- {
- return false;
- }
-
- if (ReferenceEquals(this, other))
- {
- return true;
- }
-
- return string.Equals(FileName, other.FileName) &&
- Equals(Directory, other.Directory);
- }
-
- public override bool Equals(object obj)
- {
- if (ReferenceEquals(null, obj))
- {
- return false;
- }
-
- if (ReferenceEquals(this, obj))
- {
- return true;
- }
-
- if (obj.GetType() != GetType())
- {
- return false;
- }
-
- return Equals((RelativeFilePath) obj);
- }
-
- public override int GetHashCode() => Value.GetHashCode();
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tools/RelativePath.cs b/MLS.Agent.Tools/RelativePath.cs
deleted file mode 100644
index 239fee6e6..000000000
--- a/MLS.Agent.Tools/RelativePath.cs
+++ /dev/null
@@ -1,192 +0,0 @@
-// Copyright (c) .NET Foundation and contributors. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-
-namespace MLS.Agent.Tools
-{
- public abstract class RelativePath
- {
- private string _value;
-
- protected RelativePath(string value)
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
-
- ThrowIfPathIsRooted(value);
- }
-
- private void ThrowIfPathIsRooted(string path)
- {
- if (IsPathRootedRegardlessOfOS(path))
- {
- throw new ArgumentException($"Path cannot be absolute: {path}");
- }
- }
-
- private static bool IsPathRootedRegardlessOfOS(string path)
- {
- return Path.IsPathRooted(path) ||
- path.StartsWith(@"/") ||
- path.StartsWith(@"\\") ||
- path.Substring(1).StartsWith(@":\");
- }
-
- public string Value
- {
- get => _value;
- protected set => _value = value ?? throw new ArgumentNullException(nameof(value)) ;
- }
-
- public override string ToString() => Value;
-
- private static readonly HashSet DisallowedPathChars = new HashSet(
- new char[]
- {
- '|',
- '\0',
- '\u0001',
- '\u0002',
- '\u0003',
- '\u0004',
- '\u0005',
- '\u0006',
- '\a',
- '\b',
- '\t',
- '\n',
- '\v',
- '\f',
- '\r',
- '\u000e',
- '\u000f',
- '\u0010',
- '\u0011',
- '\u0012',
- '\u0013',
- '\u0014',
- '\u0015',
- '\u0016',
- '\u0017',
- '\u0018',
- '\u0019',
- '\u001a',
- '\u001b',
- '\u001c',
- '\u001d',
- '\u001e',
- '\u001f'
- });
-
- private static readonly HashSet DisallowedFileNameChars = new HashSet(
- new char[]
- {
- '"',
- '<',
- '>',
- '|',
- '\0',
- '\u0001',
- '\u0002',
- '\u0003',
- '\u0004',
- '\u0005',
- '\u0006',
- '\a',
- '\b',
- '\t',
- '\n',
- '\v',
- '\f',
- '\r',
- '\u000e',
- '\u000f',
- '\u0010',
- '\u0011',
- '\u0012',
- '\u0013',
- '\u0014',
- '\u0015',
- '\u0016',
- '\u0016',
- '\u0017',
- '\u0018',
- '\u0019',
- '\u001a',
- '\u001b',
- '\u001c',
- '\u001d',
- '\u001e',
- '\u001f',
- ':',
- '*',
- '?',
- '\\'
- });
-
- public static string NormalizeDirectory(string directoryPath)
- {
- directoryPath = directoryPath.Replace('\\', '/');
-
- if (string.IsNullOrWhiteSpace(directoryPath))
- {
- directoryPath = "./";
- }
- else
- {
- if (!IsPathRootedRegardlessOfOS(directoryPath) &&
- !directoryPath.StartsWith(".") &&
- !directoryPath.StartsWith("..") &&
- !directoryPath.StartsWith("/"))
- {
- directoryPath = $"./{directoryPath}";
- }
-
- directoryPath = directoryPath.TrimEnd('\\', '/') + '/';
- }
-
- ThrowIfContainsDisallowedDirectoryPathChars(directoryPath);
-
- return directoryPath;
- }
-
- protected static void ThrowIfContainsDisallowedDirectoryPathChars(string path)
- {
- for (var index = 0; index < path.Length; index++)
- {
- var ch = path[index];
- if (DisallowedPathChars.Contains(ch))
- {
- throw new ArgumentException($"The character {ch} is not allowed in the path");
- }
- }
- }
-
- protected static void ThrowIfContainsDisallowedFilePathChars(string filename)
- {
- for (var index = 0; index < filename.Length; index++)
- {
- var ch = filename[index];
- if (DisallowedFileNameChars.Contains(ch))
- {
- throw new ArgumentException($"The character {ch} is not allowed in the filename");
- }
- }
- }
-
- // public static bool operator ==(RelativePath left, RelativePath right)
- // {
- // return Equals(left, right);
- // }
- //
- // public static bool operator !=(RelativePath left, RelativePath right)
- // {
- // return !Equals(left, right);
- // }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tools/RelativePathExtensions.cs b/MLS.Agent.Tools/RelativePathExtensions.cs
deleted file mode 100644
index aa2b244a0..000000000
--- a/MLS.Agent.Tools/RelativePathExtensions.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-// 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.IO;
-
-namespace MLS.Agent.Tools
-{
- public static class RelativePathExtensions
- {
- public static FileInfo Combine(
- this DirectoryInfo directory,
- RelativeFilePath filePath)
- {
- var filePart = filePath.Value;
-
- if (filePart.StartsWith("./"))
- {
- filePart = filePart.Substring(2);
- }
-
- return new FileInfo(
- Path.Combine(
- directory.FullName,
- filePart.Replace('/', Path.DirectorySeparatorChar)));
- }
-
- public static DirectoryInfo Combine(
- this DirectoryInfo directory,
- RelativeDirectoryPath directoryPath)
- {
- return new DirectoryInfo(
- Path.Combine(
- RelativePath.NormalizeDirectory(directory.FullName),
- directoryPath.Value.Replace('/', Path.DirectorySeparatorChar)));
- }
-
- public static T Match(this RelativePath path, Func directory, Func file)
- {
- switch (path)
- {
- case RelativeDirectoryPath relativeDirectoryPath:
- return directory(relativeDirectoryPath);
- case RelativeFilePath relativeFilePath:
- return file(relativeFilePath);
- default:
- throw new ArgumentOutOfRangeException($"Unexpected type derived from {nameof(RelativePath)}: {path.GetType().Name}");
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent.Tools/TypeExtensions.cs b/MLS.Agent.Tools/TypeExtensions.cs
deleted file mode 100644
index 7dccc6ea7..000000000
--- a/MLS.Agent.Tools/TypeExtensions.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// 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.IO;
-using System.Linq;
-
-namespace MLS.Agent.Tools
-{
- public static class TypeExtensions
- {
- public static string ReadManifestResource(this Type type, string resourceName)
- {
- if (type == null)
- {
- throw new ArgumentNullException(nameof(type));
- }
-
- if (string.IsNullOrWhiteSpace(resourceName))
- {
- throw new ArgumentException("Value cannot be null or whitespace.", nameof(resourceName));
- }
-
- var assembly = type.Assembly;
-
- var assemblyResourceName = assembly.GetManifestResourceNames().First(s => s.Contains(resourceName));
-
- if (string.IsNullOrWhiteSpace(assemblyResourceName))
- {
- throw new InvalidOperationException($"Cannot locate resource {resourceName} in {assembly}");
- }
-
- using (var reader = new StreamReader(assembly.GetManifestResourceStream(assemblyResourceName)))
- {
- return reader.ReadToEnd();
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/(Recipes)/BadRequestOnInvalidModelFilter.cs b/MLS.Agent/(Recipes)/BadRequestOnInvalidModelFilter.cs
deleted file mode 100644
index ab31e542d..000000000
--- a/MLS.Agent/(Recipes)/BadRequestOnInvalidModelFilter.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-using System;
-using System.Linq;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.Mvc.Filters;
-
-namespace Recipes
-{
- internal class BadRequestOnInvalidModelFilter : IActionFilter
- {
- public void OnActionExecuting(ActionExecutingContext context)
- {
- if (!context.ModelState.IsValid)
- {
- context.Result = new BadRequestObjectResult(
- context.ModelState
- .Values
- .SelectMany(e => e.Errors
- .Select(ee => ee.ErrorMessage)));
- }
- }
-
- public void OnActionExecuted(ActionExecutedContext context)
- {
- }
- }
-}
diff --git a/MLS.Agent/(Recipes)/ClientConfigurationExtensions.cs b/MLS.Agent/(Recipes)/ClientConfigurationExtensions.cs
deleted file mode 100644
index 7460ee56d..000000000
--- a/MLS.Agent/(Recipes)/ClientConfigurationExtensions.cs
+++ /dev/null
@@ -1,329 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Net.Http;
-using System.Security.Cryptography;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Web;
-using Microsoft.DotNet.Try.Protocol;
-using Microsoft.DotNet.Try.Protocol.ClientApi;
-using Microsoft.DotNet.Try.Protocol.ClientApi.GitHub;
-
-namespace Recipes
-{
- internal static class ClientConfigurationExtensions
- {
- private static readonly Regex OptionalRouteFilter = new Regex(@"/\{.+\?\}", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
-
- private static string ToSha256(string value)
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
-
- var inputBytes = Encoding.UTF8.GetBytes(value);
-
- byte[] hash;
- using (var sha256 = SHA256.Create())
- {
- hash = sha256.ComputeHash(inputBytes);
- }
-
- return Convert.ToBase64String(hash);
- }
- public static string ComputeHash(this RequestDescriptors links)
- {
- return ToSha256(links.ToJson());
- }
-
- public static string BuildUrl(this RequestDescriptor requestDescriptor, Dictionary context = null)
- {
- var url = requestDescriptor.Href;
- if (requestDescriptor.Templated && context?.Count > 0)
- {
- foreach (var entry in context)
- {
- var filter = new Regex(@"\{" + entry.Key + @"\??\}", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
- url = filter.Replace(url, $"{UrlEncode(entry.Value.ToString())}");
- }
- }
-
- return OptionalRouteFilter.Replace(url, string.Empty);
- }
-
- public static string BuildQueryString(this RequestDescriptor requestDescriptor, Dictionary context = null)
- {
- var parts = new List();
- if (context?.Count > 0)
- {
- if (context.TryGetValue("hostOrigin", out var hostOrigin))
- {
- parts.Add($"hostOrigin={UrlEncode(hostOrigin.ToString())}");
- }
-
- foreach (var property in requestDescriptor.Properties ?? Enumerable.Empty())
- {
- if (context.TryGetValue(property.Name, out var propertyValue))
- {
- parts.Add($"{property.Name}={UrlEncode(propertyValue.ToString())}");
- }
- }
- }
-
- return string.Join("&", parts);
- }
-
- public static HttpRequestMessage BuildRequest(this RequestDescriptor requestDescriptor, Dictionary context = null)
- {
- var fullUrl = requestDescriptor.BuildFullUri(context);
-
- var request = new HttpRequestMessage
- {
- RequestUri = new Uri(fullUrl, UriKind.RelativeOrAbsolute)
- };
-
- switch (requestDescriptor.Method)
- {
- case "POST":
- request.Method = HttpMethod.Post;
- break;
- case "DELETE":
- request.Method = HttpMethod.Delete;
- break;
- case "PUT":
- request.Method = HttpMethod.Put;
- break;
- case "HEAD":
- request.Method = HttpMethod.Head;
- break;
- case "OPTIONS":
- request.Method = HttpMethod.Options;
- break;
- case "TRACE":
- request.Method = HttpMethod.Trace;
- break;
- default:
- request.Method = HttpMethod.Get;
- break;
- }
-
- return request;
- }
-
- public static string BuildFullUri(this RequestDescriptor requestDescriptor, Dictionary context = null)
- {
- var url = requestDescriptor.BuildUrl(context);
- var queryString = requestDescriptor.BuildQueryString(context);
-
- var fullUrl = url;
- if (!string.IsNullOrWhiteSpace(queryString))
- {
- var joinSymbol = "?";
- if (url.IndexOf("?", StringComparison.InvariantCultureIgnoreCase) >= 0)
- {
- joinSymbol = "&";
- }
-
- fullUrl = $"{url}{joinSymbol}{queryString}";
- }
-
- return fullUrl;
- }
-
- public static HttpRequestMessage BuildLoadFromRequest(this ClientConfiguration configuration, string codeUrl, string hostOrigin)
- {
- var api = configuration.Links.Snippet;
- var context = new Dictionary
- {
- { "from", codeUrl }
- };
-
- var request = BuildRequestWithHeaders(configuration, api, hostOrigin, context);
-
- return request;
- }
-
- private static HttpRequestMessage BuildRequestWithHeaders(this ClientConfiguration configuration, RequestDescriptor requestDescriptor, string hostOrigin, Dictionary context = null)
- {
- var safeContext = context ?? new Dictionary();
-
- if (hostOrigin != null)
- {
- safeContext["hostOrigin"] = hostOrigin;
- }
-
- var request = requestDescriptor.BuildRequest(safeContext);
-
- configuration.AddConfigurationVersionIdHeader(request);
- configuration.AddTimeoutHeader(request, requestDescriptor);
-
- return request;
- }
-
- public static HttpRequestMessage BuildLoadFromGistRequest(this ClientConfiguration configuration, string gist, string hash = null, string workspaceType = null,
- bool? extractBuffers = null, string hostOrigin = null)
- {
- var api = configuration.Links.LoadFromGist;
- var context = new Dictionary
- {
- { "gistId", gist }
- };
-
- if (hash != null)
- {
- context["commitHash"] = hash;
- }
-
- if (workspaceType != null)
- {
- context["workspaceType"] = workspaceType;
- }
-
- if (extractBuffers != null)
- {
- context["extractBuffers"] = extractBuffers;
- }
-
- return BuildRequestWithHeaders(configuration, api, hostOrigin, context);
- }
-
- public static HttpRequestMessage BuildRegionFromFilesRequest(this ClientConfiguration configuration, IEnumerable files, string hostOrigin, string requestId = null)
- {
- var api = configuration.Links.RegionsFromFiles;
-
- var request = BuildRequestWithHeaders(configuration, api, hostOrigin);
- var payload = new CreateRegionsFromFilesRequest(requestId ?? (Guid.NewGuid().ToString()), files?.ToArray());
- SetRequestContent(payload, request);
-
- return request;
- }
-
- public static HttpRequestMessage BuildProjectFromGistRequest(this ClientConfiguration configuration, string gistId, string projectTemplate, string hostOrigin, string hash = null, string requestId = null)
- {
- var api = configuration.Links.ProjectFromGist;
-
- var request = BuildRequestWithHeaders(configuration, api, hostOrigin);
- var payload = new CreateProjectFromGistRequest(requestId ?? (Guid.NewGuid().ToString()), gistId, projectTemplate, hash);
- SetRequestContent(payload, request);
-
- return request;
- }
-
- public static HttpRequestMessage BuildCompletionRequest(this ClientConfiguration configuration, object workspaceRequest, string hostOrigin)
- {
- var api = configuration.Links.Completion;
-
- var request = BuildRequestWithHeaders(configuration, api, hostOrigin);
-
- SetRequestContent(workspaceRequest, request);
-
- return request;
- }
-
- public static HttpRequestMessage BuildCompileRequest(this ClientConfiguration configuration, object workspaceRequest, string hostOrigin)
- {
- var api = configuration.Links.Compile;
-
- var request = BuildRequestWithHeaders(configuration, api, hostOrigin);
-
- SetRequestContent(workspaceRequest, request);
-
- return request;
- }
-
- public static HttpRequestMessage BuildSignatureHelpRequest(this ClientConfiguration configuration, object workspaceRequest, string hostOrigin)
- {
- var api = configuration.Links.SignatureHelp;
-
- var request = BuildRequestWithHeaders(configuration, api, hostOrigin);
-
- SetRequestContent(workspaceRequest, request);
-
- return request;
- }
-
- public static HttpRequestMessage BuildDiagnosticsRequest(this ClientConfiguration configuration, object workspace, string hostOrigin)
- {
- var api = configuration.Links.Diagnostics;
-
- var request = BuildRequestWithHeaders(configuration, api, hostOrigin);
-
- SetRequestContent(workspace, request);
-
- return request;
- }
-
- public static HttpRequestMessage BuildRunRequest(this ClientConfiguration configuration, object workspaceRequest, string hostOrigin)
- {
- var api = configuration.Links.Run;
-
- var request = BuildRequestWithHeaders(configuration, api, hostOrigin);
-
- SetRequestContent(workspaceRequest, request);
-
- return request;
- }
-
- public static HttpRequestMessage BuildVersionRequest(this ClientConfiguration configuration, string hostOrigin)
- {
- var api = configuration.Links.Version;
-
- return BuildRequestWithHeaders(configuration, api, hostOrigin);
- }
-
- public static HttpRequestMessage BuildGetPackagesRequest(this ClientConfiguration configuration, string packageName, string packageVersion, string hostOrigin)
- {
- var api = configuration.Links.GetPackage;
- var context = new Dictionary
- {
- { "name", packageName },
- { "version", packageVersion }
- };
-
- var request = BuildRequestWithHeaders(configuration, api, hostOrigin, context);
-
-
- return request;
- }
-
- private static string UrlEncode(string source)
- {
- return HttpUtility.UrlEncode(HttpUtility.UrlDecode(source));
- }
-
- private static void AddConfigurationVersionIdHeader(this ClientConfiguration configuration, HttpRequestMessage request)
- {
- request.Headers.Remove("ClientConfigurationVersionId");
- request.Headers.Add("ClientConfigurationVersionId", configuration.VersionId);
- }
-
- private static void AddTimeoutHeader(this ClientConfiguration configuration, HttpRequestMessage request, RequestDescriptor requestDescriptor = null)
- {
- request.Headers.Remove("Timeout");
- var timeoutMs = configuration.DefaultTimeoutMs.ToString(CultureInfo.InvariantCulture);
-
- if (requestDescriptor != null && requestDescriptor.TimeoutMs > 0)
- {
- timeoutMs = requestDescriptor.TimeoutMs.ToString(CultureInfo.InvariantCulture);
- }
-
- request.Headers.Add("Timeout", timeoutMs);
- }
-
- private static void SetRequestContent(object content, HttpRequestMessage request)
- {
- switch (content)
- {
- case string text:
- request.Content = new JsonContent(text);
- break;
- default:
- request.Content = new JsonContent(content);
- break;
- }
- }
- }
-}
diff --git a/MLS.Agent/(Recipes)/DictionaryExtensions.cs b/MLS.Agent/(Recipes)/DictionaryExtensions.cs
deleted file mode 100644
index 98fe27886..000000000
--- a/MLS.Agent/(Recipes)/DictionaryExtensions.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-using System;
-using System.Collections.Generic;
-
-namespace Recipes
-{
- internal static class DictionaryExtensions
- {
- ///
- /// Adds a key/value pair to the dictionary if the key does not already exist.
- ///
- /// The type of the key.
- /// The type of the value.
- /// The dictionary.
- /// The key of the element to add.
- /// The function used to generate a value for the key.
- ///
- /// The value for the key. This will be either the existing value for the key if the key is already in the dictionary, or the new value for the key as returned by valueFactory if the key was not in the dictionary.
- ///
- /// dictionary
- public static TValue GetOrAdd(
- this IDictionary dictionary,
- TKey key,
- Func valueFactory)
- {
- if (dictionary == null)
- {
- throw new ArgumentNullException(nameof(dictionary));
- }
- if (valueFactory == null)
- {
- throw new ArgumentNullException(nameof(valueFactory));
- }
-
- TValue value;
- if (dictionary.TryGetValue(key, out value))
- {
- return value;
- }
-
- value = valueFactory(key);
- dictionary.Add(key, value);
- return value;
- }
- }
-}
diff --git a/MLS.Agent/(Recipes)/JsonContent.cs b/MLS.Agent/(Recipes)/JsonContent.cs
deleted file mode 100644
index bca0054bc..000000000
--- a/MLS.Agent/(Recipes)/JsonContent.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using System.Net.Http;
-using System.Text;
-
-namespace Recipes
-{
- internal class JsonContent : StringContent
- {
- public JsonContent(object content)
- : base(content.ToJson(),
- Encoding.UTF8,
- "application/json")
- {
- }
-
- public JsonContent(string content)
- : base(content,
- Encoding.UTF8,
- "application/json")
- {
- }
- }
-}
diff --git a/MLS.Agent/(Recipes)/VersionSensor.cs b/MLS.Agent/(Recipes)/VersionSensor.cs
deleted file mode 100644
index 24f1378f6..000000000
--- a/MLS.Agent/(Recipes)/VersionSensor.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System;
-using System.Diagnostics;
-using System.IO;
-using System.Reflection;
-
-namespace Recipes
-{
-#if !RecipesProject
- [DebuggerStepThrough]
-#endif
- internal partial class VersionSensor
- {
- private static readonly Lazy buildInfo = new Lazy(() =>
- {
- var assembly = typeof(VersionSensor).GetTypeInfo().Assembly;
-
- var info = new BuildInfo
- {
- AssemblyName = assembly.GetName().Name,
- AssemblyInformationalVersion = assembly
- .GetCustomAttribute()
- .InformationalVersion,
- AssemblyVersion = assembly.GetName().Version.ToString(),
- BuildDate = new FileInfo(assembly.Location).CreationTimeUtc.ToString("o")
- };
-
- AssignServiceVersionTo(info);
-
- return info;
- });
-
- public static BuildInfo Version()
- {
- return buildInfo.Value;
- }
-
- public class BuildInfo
- {
- public string AssemblyVersion { get; set; }
- public string BuildDate { get; set; }
- public string AssemblyInformationalVersion { get; set; }
- public string AssemblyName { get; set; }
- public string ServiceVersion { get; set; }
- }
-
- static partial void AssignServiceVersionTo(BuildInfo buildInfo);
- }
-}
diff --git a/MLS.Agent/ApplicationBuilderExtensions.cs b/MLS.Agent/ApplicationBuilderExtensions.cs
deleted file mode 100644
index 6b9a40ee2..000000000
--- a/MLS.Agent/ApplicationBuilderExtensions.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright (c) .NET Foundation and contributors. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.StaticFiles.Infrastructure;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.FileProviders;
-using Microsoft.Net.Http.Headers;
-using Recipes;
-
-namespace MLS.Agent
-{
- internal static class ApplicationBuilderExtensions
- {
- public static IApplicationBuilder EnableCachingBlazorContent(this IApplicationBuilder app)
- {
- return app.Use((context, next) =>
- {
- if (HttpMethods.IsGet(context.Request.Method))
- {
- context.Response.Headers[HeaderNames.CacheControl] = "public, max-age=604800";
- }
-
- return next();
- });
- }
-
- public static IApplicationBuilder UseStaticFilesFromToolLocationAndRootDirectory(this IApplicationBuilder app, DirectoryInfo rootDirectory)
- {
- var options = GetStaticFilesOptions(rootDirectory);
-
- app.UseStaticFiles();
- if (options != null)
- {
- app.UseStaticFiles(options);
- }
-
-
- return app;
- }
-
- private static StaticFileOptions GetStaticFilesOptions(DirectoryInfo rootDirectory)
- {
- var paths = new List
- {
- Path.Combine(Path.GetDirectoryName(typeof(Startup).Assembly.Location), "wwwroot"),
- rootDirectory.FullName
- };
-
- var providers = paths.Where(Directory.Exists).Select(p => new PhysicalFileProvider(p)).ToArray();
-
- StaticFileOptions options = null;
-
- if (providers.Length > 0)
- {
- var combinedProvider = new CompositeFileProvider(providers);
-
- var sharedOptions = new SharedOptions { FileProvider = combinedProvider };
- options = new StaticFileOptions(sharedOptions);
- }
-
- return options;
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Blazor/BlazorPackageConfiguration.cs b/MLS.Agent/Blazor/BlazorPackageConfiguration.cs
deleted file mode 100644
index 567d820c5..000000000
--- a/MLS.Agent/Blazor/BlazorPackageConfiguration.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-// 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.Threading.Tasks;
-using Clockwise;
-using Microsoft.AspNetCore.Builder;
-using WorkspaceServer;
-using WorkspaceServer.Packaging;
-
-namespace MLS.Agent.Blazor
-{
- internal sealed class BlazorPackageConfiguration
- {
- public static void Configure(
- IApplicationBuilder app,
- IServiceProvider serviceProvider,
- PackageRegistry registry,
- Budget budget,
- bool prepareIfNeeded)
- {
- List prepareTasks = new List();
-
- foreach (var builderFactory in registry)
- {
- var builder = builderFactory.Result;
- if (builder.BlazorSupported)
- {
- var package = (BlazorPackage) builder.GetPackage();
- if (PackageHasBeenBuiltAndHasBlazorStuff(package))
- {
- SetupMappingsForBlazorContentsOfPackage(package, app);
- }
- else if(prepareIfNeeded)
- {
- prepareTasks.Add(Task.Run(() => package.EnsureReady(budget)).ContinueWith(t => {
- if (t.IsCompletedSuccessfully)
- {
- SetupMappingsForBlazorContentsOfPackage(package, app);
- }
- }));
- }
- }
- }
-
- Task.WaitAll(prepareTasks.ToArray());
- }
-
- private static void SetupMappingsForBlazorContentsOfPackage(BlazorPackage package, IApplicationBuilder builder)
- {
- builder.Map(package.CodeRunnerPath, appBuilder =>
- {
- var blazorEntryPoint = package.BlazorEntryPointAssemblyPath;
- appBuilder.UsePathBase(package.CodeRunnerPathBase);
- appBuilder.UseClientSideBlazorFiles(blazorEntryPoint.FullName);
- });
- }
-
- private static bool PackageHasBeenBuiltAndHasBlazorStuff(BlazorPackage package)
- {
- return package.BlazorEntryPointAssemblyPath.Exists;
- }
- }
-}
diff --git a/MLS.Agent/BrowserLaunchUri.cs b/MLS.Agent/BrowserLaunchUri.cs
deleted file mode 100644
index ca54225be..000000000
--- a/MLS.Agent/BrowserLaunchUri.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// 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;
-
-namespace MLS.Agent
-{
- public class BrowserLaunchUri
- {
- public BrowserLaunchUri(string scheme, string host, ushort port)
- {
- Scheme = scheme ?? throw new ArgumentNullException(nameof(scheme));
- Host = host ?? throw new ArgumentNullException(nameof(host));
- Port = port;
- }
-
- public string Scheme { get; }
- public string Host { get; }
- public ushort Port { get; }
-
- public override string ToString()
- {
- return $"{Scheme}://{Host}:{Port}";
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/BrowserLauncher.cs b/MLS.Agent/BrowserLauncher.cs
deleted file mode 100644
index dbe4e26fc..000000000
--- a/MLS.Agent/BrowserLauncher.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-// 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.Diagnostics;
-using System.Runtime.InteropServices;
-
-namespace MLS.Agent
-{
- internal class BrowserLauncher : IBrowserLauncher
- {
- public void LaunchBrowser(Uri uri)
- {
- if (uri == null)
- {
- throw new ArgumentNullException(nameof(uri));
- }
-
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
- {
- Process.Start(new ProcessStartInfo("cmd", $"/c start {uri}"));
- }
- else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
- {
- Process.Start("xdg-open", uri.ToString());
- }
- else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- {
- Process.Start("open", uri.ToString());
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/CommandLineParser.cs b/MLS.Agent/CommandLine/CommandLineParser.cs
deleted file mode 100644
index 25c8e96e6..000000000
--- a/MLS.Agent/CommandLine/CommandLineParser.cs
+++ /dev/null
@@ -1,430 +0,0 @@
-// 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.CommandLine;
-using System.CommandLine.Builder;
-using System.CommandLine.Invocation;
-using System.CommandLine.IO;
-using System.CommandLine.Parsing;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using Clockwise;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.DotNet.Interactive.Telemetry;
-using Microsoft.Extensions.DependencyInjection;
-using MLS.Agent.Markdown;
-using MLS.Agent.Tools;
-using MLS.Repositories;
-using Recipes;
-using WorkspaceServer;
-using WorkspaceServer.Packaging;
-using CommandHandler = System.CommandLine.Invocation.CommandHandler;
-
-namespace MLS.Agent.CommandLine
-{
- public static class CommandLineParser
- {
- public delegate void StartServer(
- StartupOptions options,
- InvocationContext context);
-
- public delegate Task Install(
- InstallOptions options,
- IConsole console);
-
- public delegate Task Demo(
- DemoOptions options,
- IConsole console,
- StartServer startServer = null,
- InvocationContext invocationContext = null);
-
- public delegate Task TryGitHub(
- TryGitHubOptions options,
- IConsole console);
-
- public delegate Task Pack(
- PackOptions options,
- IConsole console);
-
- public delegate Task Verify(
- VerifyOptions options,
- IConsole console,
- StartupOptions startupOptions,
- MarkdownProcessingContext context);
-
- public delegate Task Publish(
- PublishOptions options,
- IConsole console,
- StartupOptions startupOptions,
- MarkdownProcessingContext context);
-
- public static Parser Create(
- IServiceCollection services,
- StartServer startServer = null,
- Install install = null,
- Demo demo = null,
- TryGitHub tryGithub = null,
- Pack pack = null,
- Verify verify = null,
- Publish publish = null,
- ITelemetry telemetry = null,
- IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null)
- {
- if (services == null)
- {
- throw new ArgumentNullException(nameof(services));
- }
-
- startServer ??= (startupOptions, invocationContext) =>
- Program.ConstructWebHost(startupOptions).Run();
-
- demo ??= DemoCommand.Do;
-
- tryGithub ??= (repo, console) =>
- GitHubHandler.Handler(repo,
- console,
- new GitHubRepoLocator());
-
- verify ??= VerifyCommand.Do;
-
- publish ??= PublishCommand.Do;
-
- pack ??= PackCommand.Do;
-
- install ??= InstallCommand.Do;
-
- // Setup first time use notice sentinel.
- firstTimeUseNoticeSentinel ??=
- new FirstTimeUseNoticeSentinel(VersionSensor.Version().AssemblyInformationalVersion);
-
- // Setup telemetry.
- telemetry ??= new Telemetry(
- VersionSensor.Version().AssemblyInformationalVersion,
- firstTimeUseNoticeSentinel);
- var filter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);
-
- var dirArgument = new Argument(result =>
- {
- var directory = result.Tokens
- .Select(t => t.Value)
- .FirstOrDefault();
-
- if (!string.IsNullOrEmpty(directory) &&
- !Directory.Exists(directory))
- {
- result.ErrorMessage = $"Directory does not exist: {directory}";
- return null;
- }
-
- return new FileSystemDirectoryAccessor(
- directory ??
- Directory.GetCurrentDirectory());
- }, isDefault: true)
- {
- Name = "root-directory",
- Arity = ArgumentArity.ZeroOrOne,
- Description = "The root directory for your documentation"
- };
-
- var rootCommand = StartInTryMode();
-
- rootCommand.AddCommand(StartInHostedMode());
- rootCommand.AddCommand(Demo());
- rootCommand.AddCommand(GitHub());
- rootCommand.AddCommand(Install());
- rootCommand.AddCommand(Pack());
- rootCommand.AddCommand(Verify());
- rootCommand.AddCommand(Publish());
-
- return new CommandLineBuilder(rootCommand)
- .UseDefaults()
- .UseMiddleware(async (context, next) =>
- {
- if (context.ParseResult.Errors.Count == 0)
- {
- telemetry.SendFiltered(filter, context.ParseResult);
- }
-
- // If sentinel does not exist, print the welcome message showing the telemetry notification.
- if (!firstTimeUseNoticeSentinel.Exists() && !Telemetry.SkipFirstTimeExperience)
- {
- context.Console.Out.WriteLine();
- context.Console.Out.WriteLine(Telemetry.WelcomeMessage);
-
- firstTimeUseNoticeSentinel.CreateIfNotExists();
- }
-
- if (context.ParseResult.Directives.Contains("debug") &&
- !(Clock.Current is VirtualClock))
- {
- VirtualClock.Start();
- }
-
- await next(context);
- })
- .Build();
-
- RootCommand StartInTryMode()
- {
- var command = new RootCommand
- {
- Name = "dotnet-try",
- Description = "Interactive documentation in your browser"
- };
-
- command.AddArgument(dirArgument);
-
- command.AddOption(new Option(
- "--add-package-source",
- "Specify an additional NuGet package source")
- {
- Argument = new Argument(() => new PackageSource(Directory.GetCurrentDirectory()))
- {
- Name = "NuGet source"
- }
- });
-
- command.AddOption(new Option(
- "--package",
- "Specify a Try .NET package or path to a .csproj to run code samples with")
- {
- Argument = new Argument
- {
- Name = "name or .csproj"
- }
- });
-
- command.AddOption(new Option(
- "--package-version",
- "Specify a Try .NET package version to use with the --package option")
- {
- Argument = new Argument
- {
- Name = "version"
- }
- });
-
- command.AddOption(new Option(
- "--uri",
- "Specify a URL or a relative path to a Markdown file"));
-
- command.AddOption(new Option(
- "--enable-preview-features",
- "Enable preview features"));
-
- command.AddOption(new Option(
- "--log-path",
- "Enable file logging to the specified directory")
- {
- Argument = new Argument
- {
- Name = "dir"
- }
- });
-
- command.AddOption(new Option(
- "--verbose",
- "Enable verbose logging to the console"));
-
- var portArgument = new Argument();
-
- portArgument.AddValidator(symbolResult =>
- {
- if (symbolResult.Tokens
- .Select(t => t.Value)
- .Count(value => !ushort.TryParse(value, out _)) > 0)
- {
- return "Invalid argument for --port option";
- }
-
- return null;
- });
-
- command.AddOption(new Option(
- "--port",
- "Specify the port for dotnet try to listen on")
- {
- Argument = portArgument
- });
-
- command.Handler = CommandHandler.Create((context, options) =>
- {
- services.AddSingleton(_ => PackageRegistry.CreateForTryMode(
- options.RootDirectory,
- options.AddPackageSource));
-
- startServer(options, context);
- });
-
- return command;
- }
-
- Command StartInHostedMode()
- {
- var command = new Command("hosted")
- {
- new Option(
- "--id",
- description: "A unique id for the agent instance (e.g. its development environment id).",
- getDefaultValue: () => Environment.MachineName),
- new Option(
- "--production",
- "Specifies whether the agent is being run using production resources"),
- new Option(
- "--language-service",
- "Specifies whether the agent is being run in language service-only mode"),
- new Option(
- new[]
- {
- "-k",
- "--key"
- },
- "The encryption key"),
- new Option(
- new[]
- {
- "--ai-key",
- "--application-insights-key"
- },
- "Application Insights key."),
- new Option(
- "--region-id",
- "A unique id for the agent region"),
- new Option(
- "--log-to-file",
- "Writes a log file")
- };
-
- command.Description = "Starts the Try .NET agent";
-
- command.IsHidden = true;
-
- command.Handler = CommandHandler.Create((context, options) =>
- {
- services.AddSingleton(_ => PackageRegistry.CreateForHostedMode());
- services.AddSingleton(c => new MarkdownProject(c.GetRequiredService()));
- startServer(options, context);
- });
-
- return command;
- }
-
- Command Demo()
- {
- var demoCommand = new Command(
- "demo",
- "Learn how to create Try .NET content with an interactive demo")
- {
- new Option(
- "--output",
- description: "Where should the demo project be written to?",
- getDefaultValue: () => new DirectoryInfo(Directory.GetCurrentDirectory()))
- };
-
- demoCommand.Handler = CommandHandler.Create((options, context) => { demo(options, context.Console, startServer, context); });
-
- return demoCommand;
- }
-
- Command GitHub()
- {
- var argument = new Argument
- {
- // System.CommandLine parameter binding does lookup by name,
- // so name the argument after the github command's string param
- Name = nameof(TryGitHubOptions.Repo)
- };
-
- var github = new Command("github", "Try a GitHub repo")
- {
- argument
- };
-
- github.IsHidden = true;
-
- github.Handler = CommandHandler.Create(tryGithub);
-
- return github;
- }
-
- Command Install()
- {
- var installCommand = new Command("install", "Install a Try .NET package")
- {
- new Argument
- {
- Name = nameof(InstallOptions.PackageName),
- Arity = ArgumentArity.ExactlyOne
- },
- new Option("--add-source")
- };
-
- installCommand.IsHidden = true;
-
- installCommand.Handler = CommandHandler.Create(install);
-
- return installCommand;
- }
-
- Command Pack()
- {
- var packCommand = new Command("pack", "Create a Try .NET package")
- {
- new Argument
- {
- Name = nameof(PackOptions.PackTarget)
- },
- new Option("--version", "The version of the Try .NET package"),
- new Option("--enable-wasm", "Enables web assembly code execution")
- };
-
- packCommand.IsHidden = true;
-
- packCommand.Handler = CommandHandler.Create(pack);
-
- return packCommand;
- }
-
- Command Verify()
- {
- var verifyCommand = new Command("verify", "Verify Markdown files found under the root directory.")
- {
- dirArgument
- };
-
- verifyCommand.Handler = CommandHandler.Create(verify);
-
- return verifyCommand;
- }
-
- Command Publish()
- {
- var publishCommand = new Command("publish", "Publish code from sample projects found under the root directory into Markdown files in the target directory")
- {
- new Option(
- "--format",
- description: "Format of the files to publish",
- getDefaultValue: () => PublishFormat.Markdown),
- new Option(
- "--target-directory",
- description: "The path where the output files should go. This can be the same as the root directory, which will overwrite files in place.",
- parseArgument: result =>
- {
- var directory = result.Tokens
- .Select(t => t.Value)
- .Single();
-
- return new FileSystemDirectoryAccessor(directory);
- }
- ),
- dirArgument
- };
- publishCommand.Handler = CommandHandler.Create(publish);
-
- return publishCommand;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/DemoCommand.cs b/MLS.Agent/CommandLine/DemoCommand.cs
deleted file mode 100644
index 073e3f1b3..000000000
--- a/MLS.Agent/CommandLine/DemoCommand.cs
+++ /dev/null
@@ -1,73 +0,0 @@
-// 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 MLS.Agent.Tools;
-using System;
-using System.CommandLine;
-using System.CommandLine.Invocation;
-using System.CommandLine.IO;
-using System.IO;
-using System.IO.Compression;
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.DotNet.Interactive.Utility;
-
-namespace MLS.Agent.CommandLine
-{
- public static class DemoCommand
- {
- public static Task Do(
- DemoOptions options,
- IConsole console,
- CommandLineParser.StartServer startServer = null,
- InvocationContext context = null)
- {
- var extractDemoFiles = true;
-
- if (!options.Output.Exists)
- {
- options.Output.Create();
- }
- else
- {
- if (options.Output.GetFiles().Any())
- {
- if (options.Output.GetFiles().All(f => f.Name != "QuickStart.md"))
- {
- console.Out.WriteLine($"Directory {options.Output} must be empty. To specify a directory to create the demo sample in, use: dotnet try demo --output ");
- return Task.FromResult(-1);
- }
-
- extractDemoFiles = false;
- }
- }
-
- if (extractDemoFiles)
- {
- using (var disposableDirectory = DisposableDirectory.Create())
- {
- var assembly = typeof(Program).Assembly;
-
- using (var resourceStream = assembly.GetManifestResourceStream("demo.zip"))
- {
- var zipPath = Path.Combine(disposableDirectory.Directory.FullName, "demo.zip");
-
- using (var fileStream = new FileStream(zipPath, FileMode.Create, FileAccess.Write))
- {
- resourceStream.CopyTo(fileStream);
- }
-
- ZipFile.ExtractToDirectory(zipPath, options.Output.FullName);
- }
- }
- }
-
- startServer?.Invoke(new StartupOptions(
- uri: new Uri("QuickStart.md", UriKind.Relative),
- rootDirectory: new FileSystemDirectoryAccessor(options.Output)),
- context);
-
- return Task.FromResult(0);
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/DemoOptions.cs b/MLS.Agent/CommandLine/DemoOptions.cs
deleted file mode 100644
index 949d136e7..000000000
--- a/MLS.Agent/CommandLine/DemoOptions.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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.IO;
-
-namespace MLS.Agent.CommandLine
-{
- public class DemoOptions
- {
- public DemoOptions(DirectoryInfo output)
- {
- Output = output;
- }
-
- public DirectoryInfo Output { get; }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/DirectoryExtensions.cs b/MLS.Agent/CommandLine/DirectoryExtensions.cs
deleted file mode 100644
index 77fdf49f5..000000000
--- a/MLS.Agent/CommandLine/DirectoryExtensions.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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.IO;
-using MLS.Agent.Tools;
-
-namespace MLS.Agent.CommandLine
-{
- internal static class DirectoryExtensions
- {
- private static readonly RelativeDirectoryPath _here = new RelativeDirectoryPath("./");
-
- public static bool IsChildOf(this FileSystemInfo file, IDirectoryAccessor directory)
- {
- var parent = directory.GetFullyQualifiedPath(_here).FullName;
- var child = Path.GetDirectoryName(file.FullName);
-
- child = child.EndsWith('/') || child.EndsWith('\\') ? child : child + "/";
- return IsBaseOf(parent, child, selfIsChild: true);
- }
-
- public static bool IsSubDirectoryOf(this IDirectoryAccessor potentialChild, IDirectoryAccessor directory)
- {
- var child = potentialChild.GetFullyQualifiedPath(_here).FullName;
- var parent = directory.GetFullyQualifiedPath(_here).FullName;
- return IsBaseOf(parent, child, selfIsChild: false);
- }
-
- private static bool IsBaseOf(string parent, string child, bool selfIsChild)
- {
- var parentUri = new Uri(parent);
- var childUri = new Uri(child);
- return (selfIsChild || parentUri != childUri) && parentUri.IsBaseOf(childUri);
- }
-
- public static void EnsureDirectoryExists(this IDirectoryAccessor directoryAccessor, RelativePath path)
- {
- var relativeDirectoryPath = path.Match(
- directory => directory,
- file => file.Directory
- );
- directoryAccessor.EnsureDirectoryExists(relativeDirectoryPath);
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/GithubHandler.cs b/MLS.Agent/CommandLine/GithubHandler.cs
deleted file mode 100644
index 711cda4ea..000000000
--- a/MLS.Agent/CommandLine/GithubHandler.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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 MLS.Repositories;
-using System.CommandLine;
-using System.CommandLine.IO;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace MLS.Agent.CommandLine
-{
- public static class GitHubHandler
- {
- public static async Task Handler(TryGitHubOptions options, IConsole console, IRepoLocator locator)
- {
- var repos = (await locator.LocateRepo(options.Repo)).ToArray();
-
- if (repos.Length == 0)
- {
- console.Out.WriteLine($"Didn't find any repos called `{options.Repo}`");
- }
- else if (repos[0].Name == options.Repo)
- {
- console.Out.WriteLine(GenerateCommandExample(repos[0].Name, repos[0].CloneUrl));
-
- }
- else
- {
- console.Out.WriteLine("Which of the following did you mean?");
- foreach (var instance in repos)
- {
- console.Out.WriteLine($"\t{instance.Name}");
- }
- }
-
- string GenerateCommandExample(string name, string cloneUrl)
- {
- var text = $"Found repo `{name}`\n";
- text += $"To try `{name}`, cd to your desired directory and run the following command:\n\n";
- text += $"\tgit clone {cloneUrl} && dotnet try .";
-
- return text;
- }
- }
- }
-}
diff --git a/MLS.Agent/CommandLine/InstallCommand.cs b/MLS.Agent/CommandLine/InstallCommand.cs
deleted file mode 100644
index 9020dd74f..000000000
--- a/MLS.Agent/CommandLine/InstallCommand.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-// 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.Threading.Tasks;
-using Microsoft.DotNet.Interactive.Utility;
-using MLS.Agent.Tools;
-
-namespace MLS.Agent.CommandLine
-{
- public static class InstallCommand
- {
- public static async Task Do(InstallOptions options, IConsole console)
- {
- var dotnet = new Dotnet();
- (await dotnet.ToolInstall(
- options.PackageName,
- options.Location,
- options.AddSource.ToString())).ThrowOnFailure();
-
- var tool = WorkspaceServer.WorkspaceFeatures.PackageTool.TryCreateFromDirectory(options.PackageName, new FileSystemDirectoryAccessor(options.Location));
- await tool.Prepare();
- }
- }
-}
diff --git a/MLS.Agent/CommandLine/InstallOptions.cs b/MLS.Agent/CommandLine/InstallOptions.cs
deleted file mode 100644
index 27bf43d50..000000000
--- a/MLS.Agent/CommandLine/InstallOptions.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-// 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.IO;
-using Microsoft.DotNet.Interactive.Utility;
-using WorkspaceServer;
-using WorkspaceServer.Packaging;
-
-namespace MLS.Agent.CommandLine
-{
- public class InstallOptions
- {
- public InstallOptions(string packageName, PackageSource addSource = null, DirectoryInfo location = null)
- {
- if (string.IsNullOrWhiteSpace(packageName))
- {
- throw new ArgumentException("Value cannot be null or whitespace.", nameof(packageName));
- }
- AddSource = addSource;
- PackageName = packageName;
- Location = location ?? Package.DefaultPackagesDirectory;
- }
-
- public PackageSource AddSource { get; }
-
- public string PackageName { get; }
- public DirectoryInfo Location { get; }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/MarkdownProcessingContext.cs b/MLS.Agent/CommandLine/MarkdownProcessingContext.cs
deleted file mode 100644
index 03a46802a..000000000
--- a/MLS.Agent/CommandLine/MarkdownProcessingContext.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-// 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.CommandLine;
-using System.CommandLine.IO;
-using System.IO;
-using Microsoft.DotNet.Try.Markdown;
-using MLS.Agent.Markdown;
-using MLS.Agent.Tools;
-using WorkspaceServer;
-using WorkspaceServer.Servers;
-
-namespace MLS.Agent.CommandLine
-{
- public class MarkdownProcessingContext
- {
- private readonly Lazy _lazyWorkspaceServer;
-
-
- public MarkdownProcessingContext(
- IDirectoryAccessor rootDirectory,
- IDefaultCodeBlockAnnotations defaultAnnotations = null,
- WriteFile writeFile = null,
- IConsole console = null)
- {
- RootDirectory = rootDirectory;
- Console = console ?? new SystemConsole();
-
- var packageRegistry = PackageRegistry.CreateForTryMode(rootDirectory);
-
- Project = new MarkdownProject(
- rootDirectory,
- packageRegistry,
- defaultAnnotations ?? new DefaultCodeBlockAnnotations());
-
- _lazyWorkspaceServer = new Lazy(() => new WorkspaceServerMultiplexer(packageRegistry));
-
- WriteFile = writeFile ?? File.WriteAllText;
- }
-
- public IConsole Console { get; }
-
- public IDirectoryAccessor RootDirectory { get; }
-
- public WriteFile WriteFile { get; }
-
- public MarkdownProject Project { get; }
-
- public IWorkspaceServer WorkspaceServer => _lazyWorkspaceServer.Value;
-
- public IList Errors { get; } = new List();
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/PackCommand.cs b/MLS.Agent/CommandLine/PackCommand.cs
deleted file mode 100644
index 10798d735..000000000
--- a/MLS.Agent/CommandLine/PackCommand.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-// 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.CommandLine;
-using System.CommandLine.IO;
-using System.IO;
-using System.IO.Compression;
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.DotNet.Interactive.Utility;
-using MLS.Agent.Tools;
-using WorkspaceServer.Packaging;
-
-namespace MLS.Agent.CommandLine
-{
- public static class PackCommand
- {
- public static async Task Do(PackOptions options, IConsole console)
- {
- console.Out.WriteLine($"Creating package-tool from {options.PackTarget.FullName}");
-
- using (var disposableDirectory = DisposableDirectory.Create())
- {
- var temp = disposableDirectory.Directory;
- var temp_projects = temp.CreateSubdirectory("projects");
-
- var name = options.PackageName;
-
- var temp_projects_build = temp_projects.CreateSubdirectory("build");
- options.PackTarget.CopyTo(temp_projects_build);
-
- if (options.EnableWasm)
- {
- string runnerDirectoryName = "wasm";
- var temp_projects_wasm = temp_projects.CreateSubdirectory(runnerDirectoryName);
- var temp_mlsblazor = temp.CreateSubdirectory("MLS.Blazor");
- await AddBlazorProject(temp_mlsblazor, GetProjectFile(temp_projects_build), name, temp_projects_wasm);
- }
-
- var temp_toolproject = temp.CreateSubdirectory("project");
- var archivePath = Path.Combine(temp_toolproject.FullName, "package.zip");
- ZipFile.CreateFromDirectory(temp_projects.FullName, archivePath, CompressionLevel.Fastest, includeBaseDirectory: false);
-
- console.Out.WriteLine(archivePath);
-
- var projectFilePath = Path.Combine(temp_toolproject.FullName, "package-tool.csproj");
- var contentFilePath = Path.Combine(temp_toolproject.FullName, "program.cs");
-
- await File.WriteAllTextAsync(
- projectFilePath,
- typeof(Program).ReadManifestResource("MLS.Agent.MLS.PackageTool.csproj"));
-
- await File.WriteAllTextAsync(contentFilePath, typeof(Program).ReadManifestResource("MLS.Agent.Program.cs"));
-
- var dotnet = new Dotnet(temp_toolproject);
- var result = await dotnet.Build();
-
- result.ThrowOnFailure("Failed to build intermediate project.");
- var versionArg = "";
-
- if(!string.IsNullOrEmpty(options.Version))
- {
- versionArg = $"/p:PackageVersion={options.Version}";
- }
-
- result = await dotnet.Pack($@"/p:PackageId=""{name}"" /p:ToolCommandName=""{name}"" {versionArg} ""{projectFilePath}"" -o ""{options.OutputDirectory.FullName}""");
-
- result.ThrowOnFailure("Package build failed.");
-
- return name;
- }
- }
-
- private static async Task AddBlazorProject(DirectoryInfo blazorTargetDirectory, FileInfo projectToReference, string name, DirectoryInfo wasmLocation)
- {
- var initializer = new BlazorPackageInitializer(name, new System.Collections.Generic.List<(string,string,string)>());
- await initializer.Initialize(blazorTargetDirectory);
-
- await AddReference(blazorTargetDirectory, projectToReference);
- var dotnet = new Dotnet(blazorTargetDirectory);
- var result = await dotnet.Publish($"-o {wasmLocation.FullName}");
- result.ThrowOnFailure();
- }
-
- private static async Task AddReference(DirectoryInfo blazorTargetDirectory, FileInfo projectToReference)
- {
- var dotnet = new Dotnet(blazorTargetDirectory);
- (await dotnet.AddReference(projectToReference)).ThrowOnFailure();
- }
-
- private static FileInfo GetProjectFile(DirectoryInfo directory)
- {
- return directory.GetFiles("*.csproj").Single();
- }
- }
-}
diff --git a/MLS.Agent/CommandLine/PackOptions.cs b/MLS.Agent/CommandLine/PackOptions.cs
deleted file mode 100644
index 4f187ca6d..000000000
--- a/MLS.Agent/CommandLine/PackOptions.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// 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.IO;
-using System.Linq;
-
-namespace MLS.Agent.CommandLine
-{
- public class PackOptions
- {
- private string _packageName;
-
- public PackOptions(
- DirectoryInfo packTarget,
- string version = null,
- DirectoryInfo outputDirectory = null,
- bool enableWasm = false,
- string packageName = null)
- {
- PackTarget = packTarget ?? throw new ArgumentNullException(nameof(packTarget));
- OutputDirectory = outputDirectory ?? packTarget;
- EnableWasm = enableWasm;
- Version = version;
- _packageName = packageName;
- }
-
- public DirectoryInfo PackTarget { get; }
- public DirectoryInfo OutputDirectory { get; }
- public bool EnableWasm { get; }
- public string Version { get; }
- public string PackageName
- {
- get
- {
- if (!string.IsNullOrEmpty(_packageName))
- {
- return _packageName;
- }
-
- var csproj = PackTarget.GetFiles("*.csproj").Single();
- _packageName = Path.GetFileNameWithoutExtension(csproj.Name);
- return _packageName;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/PublishCommand.cs b/MLS.Agent/CommandLine/PublishCommand.cs
deleted file mode 100644
index 9dfd402f4..000000000
--- a/MLS.Agent/CommandLine/PublishCommand.cs
+++ /dev/null
@@ -1,204 +0,0 @@
-// 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.CommandLine;
-using System.CommandLine.IO;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using Markdig;
-using Markdig.Renderers;
-using Markdig.Renderers.Normalize;
-using Markdig.Syntax;
-using Microsoft.DotNet.Try.Markdown;
-using Microsoft.DotNet.Try.Protocol;
-using MLS.Agent.Markdown;
-using MLS.Agent.Tools;
-
-namespace MLS.Agent.CommandLine
-{
- public delegate void WriteFile(string path, string content);
-
-
- public static class PublishCommand
- {
- public static async Task Do(
- PublishOptions publishOptions,
- IConsole console,
- StartupOptions startupOptions = null,
- MarkdownProcessingContext context = null)
- {
- context ??= new MarkdownProcessingContext(
- publishOptions.RootDirectory,
- startupOptions,
- console: console);
-
- var verifyResult = await VerifyCommand.Do(
- publishOptions,
- console,
- startupOptions,
- context);
-
- if (verifyResult != 0)
- {
- return verifyResult;
- }
-
- var targetIsSubDirectoryOfSource =
- publishOptions.TargetDirectory
- .IsSubDirectoryOf(publishOptions.RootDirectory);
-
- foreach (var markdownFile in context.Project.GetAllMarkdownFiles())
- {
- var fullSourcePath = publishOptions.RootDirectory.GetFullyQualifiedPath(markdownFile.Path);
-
- if (targetIsSubDirectoryOfSource &&
- fullSourcePath.IsChildOf(publishOptions.TargetDirectory))
- {
- continue;
- }
-
- var sessions = await markdownFile.GetSessions();
-
- var outputsBySessionName = new Dictionary();
-
- foreach (var session in sessions)
- {
- if (session.CodeBlocks.Any(b => b.Annotations is OutputBlockAnnotations))
- {
- var workspace = await session.GetWorkspaceAsync();
-
- var runArgs =
- session.CodeBlocks
- .Select(c => c.Annotations)
- .OfType()
- .Select(a => a.RunArgs)
- .FirstOrDefault();
-
- var request = new WorkspaceRequest(
- workspace,
- runArgs: runArgs);
-
- var result = await context.WorkspaceServer.Run(request);
-
- if (result.Succeeded)
- {
- var output = result.Output.Count > 0
- ? string.Join("\n", result.Output)
- : result.Exception;
-
- outputsBySessionName.Add(
- session.Name,
- output);
- }
- else
- {
- context.Errors.Add(
- $"Running session {session.Name} failed:\n" + result.Exception);
- }
- }
- }
-
- var document = ParseMarkdownDocument(markdownFile);
-
- var rendered = await Render(
- publishOptions.Format,
- document,
- outputsBySessionName);
-
- var targetPath = WriteTargetFile(
- rendered,
- markdownFile.Path,
- publishOptions,
- context,
- publishOptions.Format);
-
- console.Out.WriteLine($"Published '{fullSourcePath}' to {targetPath}");
- }
-
- return 0;
- }
-
- private static string WriteTargetFile(
- string content,
- RelativeFilePath relativePath,
- PublishOptions publishOptions,
- MarkdownProcessingContext context,
- PublishFormat format)
- {
- context.Project
- .DirectoryAccessor
- .EnsureDirectoryExists(relativePath);
-
- var targetPath = publishOptions
- .TargetDirectory
- .GetFullyQualifiedPath(relativePath).FullName;
-
- if (format == PublishFormat.HTML)
- {
- targetPath = Path.ChangeExtension(targetPath, ".html");
- }
-
- context.WriteFile(targetPath, content);
-
- return targetPath;
- }
-
- private static async Task Render(
- PublishFormat format,
- MarkdownDocument document,
- Dictionary outputsBySessionName)
- {
- MarkdownPipeline pipeline;
- IMarkdownRenderer renderer;
- var writer = new StringWriter();
- switch (format)
- {
- case PublishFormat.Markdown:
- pipeline = new MarkdownPipelineBuilder()
- .UseNormalizeCodeBlockAnnotations(outputsBySessionName)
- .Build();
- var normalizeRenderer = new NormalizeRenderer(writer);
- normalizeRenderer.Writer.NewLine = "\n";
- renderer = normalizeRenderer;
- break;
- case PublishFormat.HTML:
- pipeline = new MarkdownPipelineBuilder()
- .UseCodeBlockAnnotations(inlineControls: false)
- .Build();
- renderer = new HtmlRenderer(writer);
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(format), format, null);
- }
-
- pipeline.Setup(renderer);
-
- var blocks = document
- .OfType()
- .OrderBy(c => c.Order)
- .ToList();
-
- await Task.WhenAll(blocks.Select(b => b.InitializeAsync()));
-
- renderer.Render(document);
- writer.Flush();
-
- var rendered = writer.ToString();
- return rendered;
- }
-
- private static MarkdownDocument ParseMarkdownDocument(MarkdownFile markdownFile)
- {
- var pipeline = markdownFile.Project.GetMarkdownPipelineFor(markdownFile.Path);
-
- var markdown = markdownFile.ReadAllText();
-
- return Markdig.Markdown.Parse(
- markdown,
- pipeline);
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/PublishFormat.cs b/MLS.Agent/CommandLine/PublishFormat.cs
deleted file mode 100644
index e9f151f84..000000000
--- a/MLS.Agent/CommandLine/PublishFormat.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-// 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 MLS.Agent.CommandLine
-{
- public enum PublishFormat
- {
- Markdown,
- HTML
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/PublishOptions.cs b/MLS.Agent/CommandLine/PublishOptions.cs
deleted file mode 100644
index 448531ddf..000000000
--- a/MLS.Agent/CommandLine/PublishOptions.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// 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 MLS.Agent.Tools;
-
-namespace MLS.Agent.CommandLine
-{
- public class PublishOptions : VerifyOptions
- {
- public PublishOptions(
- IDirectoryAccessor rootDirectory,
- IDirectoryAccessor targetDirectory = null,
- PublishFormat format = PublishFormat.Markdown) : base(rootDirectory)
- {
- Format = format;
- TargetDirectory = targetDirectory ?? rootDirectory;
- }
-
- public IDirectoryAccessor TargetDirectory { get; }
-
- public PublishFormat Format { get; }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/StartupMode.cs b/MLS.Agent/CommandLine/StartupMode.cs
deleted file mode 100644
index b9c3feec6..000000000
--- a/MLS.Agent/CommandLine/StartupMode.cs
+++ /dev/null
@@ -1,11 +0,0 @@
-// 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 MLS.Agent.CommandLine
-{
- public enum StartupMode
- {
- Hosted,
- Try
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/StartupOptions.cs b/MLS.Agent/CommandLine/StartupOptions.cs
deleted file mode 100644
index 38e978ad7..000000000
--- a/MLS.Agent/CommandLine/StartupOptions.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-// 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.CommandLine.Parsing;
-using System.IO;
-using Microsoft.DotNet.Try.Markdown;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Hosting;
-using MLS.Agent.Tools;
-using WorkspaceServer.Packaging;
-
-namespace MLS.Agent.CommandLine
-{
- public class StartupOptions : IDefaultCodeBlockAnnotations
- {
- private readonly ParseResult _parseResult;
-
- public static StartupOptions FromCommandLine(string commandLine)
- {
- StartupOptions startupOptions = null;
-
- CommandLineParser.Create(new ServiceCollection(), startServer: (options, context) =>
- {
- startupOptions = options;
- })
- .InvokeAsync(commandLine);
-
- return startupOptions;
- }
-
- public StartupOptions(
- bool production = false,
- bool languageService = false,
- string key = null,
- string applicationInsightsKey = null,
- string id = null,
- string regionId = null,
- PackageSource addPackageSource = null,
- Uri uri = null,
- DirectoryInfo logPath = null,
- bool verbose = false,
- bool enablePreviewFeatures = false,
- string package = null,
- string packageVersion = null,
- ParseResult parseResult = null,
- ushort? port = null,
- IDirectoryAccessor rootDirectory = null)
- {
- _parseResult = parseResult;
- LogPath = logPath;
- Verbose = verbose;
- Id = id;
- Production = production;
- IsLanguageService = languageService;
- Key = key;
- ApplicationInsightsKey = applicationInsightsKey;
- RegionId = regionId;
- RootDirectory = rootDirectory?? new FileSystemDirectoryAccessor(new DirectoryInfo(Directory.GetCurrentDirectory()));
- AddPackageSource = addPackageSource;
- Uri = uri;
- EnablePreviewFeatures = enablePreviewFeatures;
- Package = package;
- PackageVersion = packageVersion;
- Port = port;
- }
-
-
- public bool EnablePreviewFeatures { get; }
- public string Id { get; }
- public string RegionId { get; }
- public IDirectoryAccessor RootDirectory { get; }
- public PackageSource AddPackageSource { get; }
- public Uri Uri { get; set; }
- public bool Production { get; }
- public bool IsLanguageService { get; set; }
- public string Key { get; }
- public string ApplicationInsightsKey { get; }
-
- public StartupMode Mode
- {
- get
- {
- switch (_parseResult?.CommandResult?.Command?.Name)
- {
- case "hosted":
- return StartupMode.Hosted;
- default:
- return StartupMode.Try;
- }
- }
- }
-
- public string EnvironmentName =>
- Production || Mode != StartupMode.Hosted
- ? Environments.Production
- : Environments.Development;
-
- public DirectoryInfo LogPath { get; }
-
- public bool Verbose { get; }
-
- public string Package { get; }
-
- public string PackageVersion { get; }
- public ushort? Port { get; }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/TryGitHubOptions.cs b/MLS.Agent/CommandLine/TryGitHubOptions.cs
deleted file mode 100644
index c7dc68d81..000000000
--- a/MLS.Agent/CommandLine/TryGitHubOptions.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-// 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 MLS.Agent.CommandLine
-{
- public class TryGitHubOptions
- {
- public TryGitHubOptions(string repo)
- {
- Repo = repo;
- }
-
- public string Repo { get; }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/VerifyCommand.cs b/MLS.Agent/CommandLine/VerifyCommand.cs
deleted file mode 100644
index dfb029eb0..000000000
--- a/MLS.Agent/CommandLine/VerifyCommand.cs
+++ /dev/null
@@ -1,237 +0,0 @@
-// 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.CommandLine;
-using System.CommandLine.IO;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Microsoft.DotNet.Try.Markdown;
-using Microsoft.DotNet.Try.Protocol;
-using MLS.Agent.Markdown;
-using MLS.Agent.Tools;
-
-namespace MLS.Agent.CommandLine
-{
- public static class VerifyCommand
- {
- public static async Task Do(
- VerifyOptions verifyOptions,
- IConsole console,
- StartupOptions startupOptions = null,
- MarkdownProcessingContext context = null)
- {
- context ??= new MarkdownProcessingContext(
- verifyOptions.RootDirectory,
- startupOptions,
- console: console);
-
- var markdownFiles = context.Project.GetAllMarkdownFiles().ToArray();
-
- console.Out.WriteLine("Verifying...");
-
- if (markdownFiles.Length == 0)
- {
- console.Error.WriteLine($"No markdown files found under {context.RootDirectory.GetFullyQualifiedRoot()}");
- return -1;
- }
-
- foreach (var markdownFile in markdownFiles)
- {
- var fullName = context.RootDirectory.GetFullyQualifiedPath(markdownFile.Path).FullName;
-
- var markdownFileDir = context.RootDirectory.GetDirectoryAccessorForRelativePath(markdownFile.Path.Directory);
-
- console.Out.WriteLine();
- console.Out.WriteLine(fullName);
- console.Out.WriteLine(new string('-', fullName.Length));
-
- foreach (var session in await markdownFile.GetSessions())
- {
- var sessionProjectOrPackageNames =
- session
- .CodeBlocks
- .Where(a => a.Annotations is CodeBlockAnnotations)
- .Select(block => block.ProjectOrPackageName())
- .Distinct();
-
- if (sessionProjectOrPackageNames.Count() != 1)
- {
- var error = $"Session cannot span projects or packages: --session {session.Name}";
- AddError(error, context);
- continue;
- }
-
- foreach (var block in session.CodeBlocks)
- {
- VerifyAnnotationReferences(
- block,
- markdownFileDir,
- console,
- context);
- }
-
- Console.ResetColor();
-
- if (!session.CodeBlocks.Any(block => block.Diagnostics.Any()))
- {
- await Compile(
- session,
- context);
- }
-
- Console.ResetColor();
- }
- }
-
- if (context.Errors.Count > 0)
- {
- Console.ForegroundColor = ConsoleColor.Red;
- }
- else
- {
- Console.ForegroundColor = ConsoleColor.Green;
- }
-
- console.Out.WriteLine($"\nFound {context.Errors.Count} error(s)");
-
- Console.ResetColor();
-
- return context.Errors.Count == 0
- ? 0
- : 1;
- }
-
- private static void VerifyAnnotationReferences(
- AnnotatedCodeBlock annotatedCodeBlock,
- IDirectoryAccessor markdownFileDir,
- IConsole console,
- MarkdownProcessingContext context)
- {
- Console.ResetColor();
-
- console.Out.WriteLine(" Checking Markdown...");
-
- var diagnostics = annotatedCodeBlock.Diagnostics.ToArray();
- var hasDiagnostics = diagnostics.Any();
-
- if (hasDiagnostics)
- {
- Console.ForegroundColor = ConsoleColor.Red;
- }
- else
- {
- Console.ForegroundColor = ConsoleColor.Green;
- }
-
- if (annotatedCodeBlock.Annotations is LocalCodeBlockAnnotations annotations)
- {
- var file = annotations?.SourceFile ?? annotations?.DestinationFile;
- var fullyQualifiedPath = file != null
- ? markdownFileDir.GetFullyQualifiedPath(file).FullName
- : "UNKNOWN";
-
- var project = annotatedCodeBlock.ProjectOrPackageName() ?? "UNKNOWN";
-
- var symbol = hasDiagnostics
- ? "X"
- : "✓";
-
- var error = $" {symbol} Line {annotatedCodeBlock.Line + 1}:\t{fullyQualifiedPath} (in project {project})";
-
- if (hasDiagnostics)
- {
- context.Errors.Add(error);
- }
-
- console.Out.WriteLine(error);
- }
-
- foreach (var diagnostic in diagnostics)
- {
- console.Out.WriteLine($"\t\t{diagnostic}");
- }
- }
-
- internal static void AddError(
- string error,
- MarkdownProcessingContext context)
- {
- Console.ForegroundColor = ConsoleColor.Red;
-
- context.Errors.Add(error);
-
- context.Console.Out.WriteLine(error);
- }
-
- internal static async Task Compile(
- Session session,
- MarkdownProcessingContext context)
- {
- var region = session.CodeBlocks
- .Select(b => b.Annotations)
- .OfType()
- .Select(a => a.Region)
- .Distinct()
- .First();
-
- var description = session.CodeBlocks.Count == 1 || string.IsNullOrWhiteSpace(session.Name)
- ? $"region \"{region}\""
- : $"session \"{session.Name}\"";
-
- context.Console.Out.WriteLine($"\n Compiling samples for {description}\n");
-
- var workspace = await session.GetWorkspaceAsync();
-
- if (!session.IsProjectCompatibleWithLanguage)
- {
- var error = $" Build failed as project {session.ProjectOrPackageName} is not compatible with language {session.Language}";
- AddError(error, context);
- }
-
- var result = await context.WorkspaceServer.Compile(new WorkspaceRequest(workspace));
-
- var projectDiagnostics = result.GetFeature()
- .Where(e => e.Severity == DiagnosticSeverity.Error)
- .ToArray();
- if (projectDiagnostics.Any())
- {
- var error = new StringBuilder();
- error.AppendLine($" Build failed for project {session.ProjectOrPackageName}");
-
- foreach (var diagnostic in projectDiagnostics)
- {
- error.AppendLine($"\t\t{diagnostic.Location}: {diagnostic.Message}");
- }
-
- AddError(error.ToString(), context);
- }
- else
- {
- var symbol = !result.Succeeded
- ? "X"
- : "✓";
-
- if (result.Succeeded)
- {
- Console.ForegroundColor = ConsoleColor.Green;
-
- context.Console.Out.WriteLine($" {symbol} No errors found within samples for {description}");
- }
- else
- {
- var error = new StringBuilder();
- error.AppendLine($" {symbol} Errors found within samples for {description}");
-
- foreach (var diagnostic in result.GetFeature())
- {
- error.AppendLine($"\t\t{diagnostic.Message}");
- }
-
- AddError(error.ToString(), context);
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/VerifyOptions.cs b/MLS.Agent/CommandLine/VerifyOptions.cs
deleted file mode 100644
index d07f39cc2..000000000
--- a/MLS.Agent/CommandLine/VerifyOptions.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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 MLS.Agent.Tools;
-
-namespace MLS.Agent.CommandLine
-{
- public class VerifyOptions
- {
- public VerifyOptions(IDirectoryAccessor rootDirectory)
- {
- RootDirectory = rootDirectory ?? throw new System.ArgumentNullException(nameof(rootDirectory));
- }
-
- public IDirectoryAccessor RootDirectory { get; }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/CommandLine/VerifyResult.cs b/MLS.Agent/CommandLine/VerifyResult.cs
deleted file mode 100644
index cf757aa53..000000000
--- a/MLS.Agent/CommandLine/VerifyResult.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-// 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 MLS.Agent.CommandLine
-{
- internal class VerifyResult
- {
- public VerifyResult(int errorCount)
- {
- ErrorCount = errorCount;
- }
-
- public int ErrorCount { get; }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Controllers/ClientConfigurationController.cs b/MLS.Agent/Controllers/ClientConfigurationController.cs
deleted file mode 100644
index 54f9d6880..000000000
--- a/MLS.Agent/Controllers/ClientConfigurationController.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-// 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.IO;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.DotNet.Try.Protocol;
-using Pocket;
-using Recipes;
-using static Pocket.Logger;
-using HttpRequest = Microsoft.AspNetCore.Http.HttpRequest;
-
-namespace MLS.Agent.Controllers
-{
- public class ClientConfigurationController : Controller
- {
- private const string ClientConfiguration = "/clientConfiguration";
- public static RequestDescriptor ClientConfigurationApi => new RequestDescriptor(ClientConfiguration);
-
- [HttpPost]
- [Route(ClientConfiguration)]
- public async Task ConfigurationAsync()
- {
- using (var operation = Log.ConfirmOnExit())
- {
- var requestBody = await ReadBody(Request);
-
- var links = new RequestDescriptors(new RequestDescriptor(Request.Path, Request.Method, requestBody: requestBody))
- {
- Configuration = ClientConfigurationController.ClientConfigurationApi,
- Completion = LanguageServicesController.CompletionApi,
- AcceptCompletion = new RequestDescriptor("{acceptanceUri}", templated: true),
- LoadFromGist = new RequestDescriptor("/workspace/fromgist/{gistId}/{commitHash?}", method: "GET",templated: true,
- properties: new[]
- {
- new RequestDescriptorProperty("workspaceType"),
- new RequestDescriptorProperty("extractBuffers")
- }),
- Diagnostics = LanguageServicesController.DiagnosticsApi,
- SignatureHelp = LanguageServicesController.SignatureHelpApi,
- Snippet = new RequestDescriptor("/snippet",method: "GET",
- properties: new[]
- {
- new RequestDescriptorProperty("from"),
- }),
- Run = RunController.RunApi,
- Compile = CompileController.CompileApi,
- Version = SensorsController.VersionApi,
- ProjectFromGist = new RequestDescriptor("/project/fromGist"),
- RegionsFromFiles = ProjectController.RegionsFromFilesApi,
- GetPackage = PackagesController.GetPackageApi
- };
-
- var versionId = links.ComputeHash();
- var clientConfig = new ClientConfiguration(versionId, links, 30000, string.Empty, false);
- operation.Succeed();
- return Ok(clientConfig);
- }
- }
-
- private static async Task ReadBody(HttpRequest request)
- {
- string body = null;
- if (request.Body != null)
- {
- using (var reader = new StreamReader(request.Body))
- {
- body = await reader.ReadToEndAsync();
- }
- }
- return body;
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Controllers/CompileController.cs b/MLS.Agent/Controllers/CompileController.cs
deleted file mode 100644
index e53b2a925..000000000
--- a/MLS.Agent/Controllers/CompileController.cs
+++ /dev/null
@@ -1,74 +0,0 @@
-// 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 Clockwise;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.DotNet.Try.Protocol;
-using MLS.Agent.Middleware;
-using Pocket;
-using WorkspaceServer.Servers;
-using static Pocket.Logger;
-
-namespace MLS.Agent.Controllers
-{
- public class CompileController : Controller
- {
- private const string CompileRoute = "/workspace/compile";
- public static RequestDescriptor CompileApi => new RequestDescriptor(CompileRoute, timeoutMs: 600000);
-
-
- private readonly IWorkspaceServer _workspaceServer;
- private readonly CompositeDisposable _disposables = new CompositeDisposable();
-
- public CompileController(
- IWorkspaceServer workspaceServer)
- {
- _workspaceServer = workspaceServer;
- }
-
- [HttpPost]
- [Route(CompileRoute)]
- [DebugEnableFilter]
- public async Task Compile(
- [FromBody] WorkspaceRequest request,
- [FromHeader(Name = "Timeout")] string timeoutInMilliseconds = "45000")
- {
- using (var operation = Log.OnEnterAndConfirmOnExit())
- {
- var workspaceType = request.Workspace.WorkspaceType;
-
- operation.Info("Compiling workspaceType {workspaceType}", workspaceType);
-
- if (!int.TryParse(timeoutInMilliseconds, out var timeoutMs))
- {
- return BadRequest();
- }
-
- if (string.Equals(workspaceType, "script", StringComparison.OrdinalIgnoreCase))
- {
- return BadRequest();
- }
-
- var runTimeout = TimeSpan.FromMilliseconds(timeoutMs);
- var budget = new TimeBudget(runTimeout);
-
- var result = await _workspaceServer.Compile(request, budget);
- budget.RecordEntry();
- operation.Succeed();
- return Ok(result);
- }
- }
-
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- _disposables.Dispose();
- }
-
- base.Dispose(disposing);
- }
- }
-}
diff --git a/MLS.Agent/Controllers/DisplayExtensions.cs b/MLS.Agent/Controllers/DisplayExtensions.cs
deleted file mode 100644
index fe4bd4690..000000000
--- a/MLS.Agent/Controllers/DisplayExtensions.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-// 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.Net.Http;
-using System.Text;
-using System.Threading.Tasks;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-
-namespace MLS.Agent.Controllers
-{
- public static class DisplayExtensions
- {
- public static async Task ToDisplayString(this HttpResponseMessage response)
- {
- var sb = new StringBuilder();
-
- sb.Append("Status code: ");
- sb.Append((int) response.StatusCode);
- sb.Append(" ");
- sb.Append(response.ReasonPhrase);
- sb.AppendLine();
-
- sb.AppendLine("Content headers:");
-
- foreach (var header in response.Headers.Concat(response.Content.Headers))
- {
- sb.Append(" ");
- sb.Append(header.Key);
- sb.Append(": ");
- sb.Append(string.Join("; ", header.Value));
- sb.AppendLine();
- }
-
- sb.AppendLine("Content:");
-
- var content = await response.Content.ReadAsStringAsync();
-
- try
- {
- var json = JToken.Parse(content);
-
- sb.Append(json.ToString(Formatting.Indented));
-
- sb.Replace("\r\n", "\n");
- }
- catch (JsonReaderException)
- {
- sb.Append(content);
- }
-
- return sb.ToString().Split("\n");
- }
- }
-}
diff --git a/MLS.Agent/Controllers/DocumentationController.cs b/MLS.Agent/Controllers/DocumentationController.cs
deleted file mode 100644
index 9cb825095..000000000
--- a/MLS.Agent/Controllers/DocumentationController.cs
+++ /dev/null
@@ -1,285 +0,0 @@
-// 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.Text;
-using System.Threading.Tasks;
-using Microsoft.ApplicationInsights.AspNetCore.Extensions;
-using Microsoft.AspNetCore.Html;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.DotNet.Try.Markdown;
-using MLS.Agent.CommandLine;
-using MLS.Agent.Markdown;
-using MLS.Agent.Tools;
-using Recipes;
-using WorkspaceServer;
-using WorkspaceServer.Packaging;
-
-namespace MLS.Agent.Controllers
-{
- public class DocumentationController : Controller
- {
- private readonly MarkdownProject _markdownProject;
- private readonly StartupOptions _startupOptions;
- private readonly PackageRegistry _packageRegistry;
- private static readonly string _cacheBuster = VersionSensor.Version().AssemblyVersion;
-
- public DocumentationController(MarkdownProject markdownProject, StartupOptions startupOptions, PackageRegistry packageRegistry)
- {
- _markdownProject = markdownProject ??
- throw new ArgumentNullException(nameof(markdownProject));
- _startupOptions = startupOptions;
- _packageRegistry = packageRegistry ??
- throw new ArgumentNullException(nameof(packageRegistry));
- }
-
- [HttpGet]
- [Route("{*path:regex(.*.md?$)}")]
- public async Task ShowMarkdownFile(string path)
- {
- if (_startupOptions.Mode != StartupMode.Try)
- {
- return NotFound();
- }
-
- var relativeFilePath = new RelativeFilePath(path);
-
- if (!_markdownProject.TryGetMarkdownFile(relativeFilePath, out var markdownFile))
- {
- return NotFound();
- }
-
- var hostUrl = Request.GetUri();
-
- var blocks = (await markdownFile.GetEditableAnnotatedCodeBlocks()).ToArray();
-
- var maxEditorPerSession = blocks.Length > 0
- ? blocks
- .GroupBy(b => b.Annotations.Session)
- .Max(editors => editors.Count())
- : 0;
-
- var pipeline = _markdownProject.GetMarkdownPipelineFor(markdownFile.Path);
-
- var extension = pipeline.Extensions.FindExact();
-
- if (extension != null)
- {
- extension.InlineControls = maxEditorPerSession <= 1;
- extension.EnablePreviewFeatures = _startupOptions.EnablePreviewFeatures;
-
- }
-
-
-
- var content = maxEditorPerSession <= 1
- ? await OneColumnLayoutScaffold(
- $"{hostUrl.Scheme}://{hostUrl.Authority}",
- markdownFile)
- : await TwoColumnLayoutScaffold(
- $"{hostUrl.Scheme}://{hostUrl.Authority}",
- markdownFile);
-
- return Content(content.ToString(), "text/html");
- }
-
- [HttpGet]
- [Route("/")]
- public async Task ShowIndex()
- {
- const string documentSvg = "";
- var links = string.Join(
- "\n",
- _markdownProject.GetAllMarkdownFiles()
- .Select(f =>
- $@"{documentSvg}{f.Path.Value}"));
-
- return Content(Index(links).ToString(), "text/html");
- }
-
-
- public static async Task SessionControlsHtml(MarkdownFile markdownFile, bool enablePreviewFeatures = false)
- {
- var sessions = (await markdownFile
- .GetAnnotatedCodeBlocks())
- .GroupBy(b => b.Annotations.Session);
-
- var sb = new StringBuilder();
-
- foreach (var session in sessions)
- {
- sb.AppendLine(
- $@"");
-
- sb.AppendLine(enablePreviewFeatures
- ? $@""
- : $@"");
- }
-
- return new HtmlString(sb.ToString());
- }
-
- private async Task GetAutoEnableOptions(MarkdownFile file)
- {
- bool useWasmRunner;
-
- if (_startupOptions.Package != null)
- {
- var package = await _packageRegistry.Get(_startupOptions.Package);
- useWasmRunner = package.CanSupportWasm;
- }
- else
- {
- var blocks = await file.GetAnnotatedCodeBlocks();
-
- var packageUsesWasm = await Task.WhenAll(blocks
- .Select(b => b.PackageName())
- .Where(p => !string.IsNullOrWhiteSpace(p))
- .Select(async name => (await _packageRegistry.Get(name))?.CanSupportWasm ?? false));
-
- useWasmRunner = packageUsesWasm.Any(p => p);
- }
-
- var requestUri = Request.GetUri();
-
- var hostUrl = $"{requestUri.Scheme}://{requestUri.Authority}";
- return new AutoEnableOptions(hostUrl, useWasmRunner);
- }
-
- private class AutoEnableOptions
- {
- public AutoEnableOptions(string apiBaseAddress, bool useWasmRunner)
- {
- ApiBaseAddress = apiBaseAddress;
- UseWasmRunner = useWasmRunner;
- }
-
- public string ApiBaseAddress { get; }
-
- public bool UseWasmRunner { get; }
- }
-
- private IHtmlContent Layout(
- string hostUrl,
- MarkdownFile markdownFile,
- IHtmlContent content,
- AutoEnableOptions autoEnableOptions) =>
- $@"
-
-
-
-
-
-
-
-
- {MathSupport()}
- dotnet try - {markdownFile.Path.Value.HtmlEncode()}
-
-
-
- {Header()}
-
-
- {Footer()}
-
-
-
-
-".ToHtmlContent();
-
- private IHtmlContent MathSupport() =>
- @"
-
- ".ToHtmlContent();
-
- private async Task OneColumnLayoutScaffold(string hostUrl, MarkdownFile markdownFile) =>
- Layout(
- hostUrl,
- markdownFile,
- await DocumentationDiv(markdownFile),
- await GetAutoEnableOptions(markdownFile));
-
- private static async Task DocumentationDiv(MarkdownFile markdownFile) =>
- $@"
- {await markdownFile.ToHtmlContentAsync()}
-
".ToHtmlContent();
-
- private async Task TwoColumnLayoutScaffold(string hostUrl, MarkdownFile markdownFile) =>
- Layout(hostUrl, markdownFile,
- $@"{await DocumentationDiv(markdownFile)}
-
- {await SessionControlsHtml(markdownFile, _startupOptions.EnablePreviewFeatures)}
-
".ToHtmlContent(),
- await GetAutoEnableOptions(markdownFile));
-
- private IHtmlContent Index(string html) =>
- $@"
-
-
-
-
-
-
- dotnet try - {_startupOptions.RootDirectory.GetFullyQualifiedRoot().FullName.HtmlEncode()}
-
-
-
- {Header()}
-
-
- {Footer()}
-
-
-
-".ToHtmlContent();
-
- private IHtmlContent Header() => $@"
-".ToHtmlContent();
-
- private IHtmlContent Footer() => @"
-".ToHtmlContent();
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Controllers/EmbeddableController.cs b/MLS.Agent/Controllers/EmbeddableController.cs
deleted file mode 100644
index 18203db56..000000000
--- a/MLS.Agent/Controllers/EmbeddableController.cs
+++ /dev/null
@@ -1,76 +0,0 @@
-// 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.Web;
-using Microsoft.AspNetCore.Mvc;
-using Newtonsoft.Json;
-using Recipes;
-
-namespace MLS.Agent.Controllers
-{
- public class EmbeddableController : Controller
- {
-
- [HttpGet]
- [Route("/ide")]
- [Route("/editor")]
- [Route("/v2/ide")]
- [Route("/v2/editor")]
- public IActionResult Html()
- {
- return Content($@"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-", "text/html");
- }
-
- private string GetClientParameters()
- {
- // Uncomment to enable testing /ide without going through orchestrator
- // var referrer = "http://localhost:4242";
- var referrer = HttpContext.Request.Headers["referer"].ToString();
-
- if (!string.IsNullOrWhiteSpace(referrer) && Uri.TryCreate(referrer, UriKind.Absolute, out var uri))
- {
- var parameters = new ClientParameters
- {
- Referrer = uri
- };
-
- return HttpUtility.HtmlAttributeEncode(parameters.ToJson());
- }
-
- return new object().ToJson();
- }
-
- public class ClientParameters
- {
- [JsonProperty("workspaceType", NullValueHandling = NullValueHandling.Ignore)]
- public string WorkspaceType { get; set; }
-
- [JsonProperty("useWasmRunner", NullValueHandling = NullValueHandling.Ignore)]
- public bool? UseWasmRunner { get; set; }
-
- [JsonProperty("scaffold", NullValueHandling = NullValueHandling.Ignore)]
- public string Scaffold { get; set; }
-
- [JsonProperty("referrer", NullValueHandling = NullValueHandling.Ignore)]
- public Uri Referrer { get; set; }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Controllers/LanguageServicesController.cs b/MLS.Agent/Controllers/LanguageServicesController.cs
deleted file mode 100644
index 4280c8b23..000000000
--- a/MLS.Agent/Controllers/LanguageServicesController.cs
+++ /dev/null
@@ -1,144 +0,0 @@
-// 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.Diagnostics;
-using System.Threading.Tasks;
-using Clockwise;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.DotNet.Try.Protocol;
-using MLS.Agent.Middleware;
-using Pocket;
-using WorkspaceServer;
-using WorkspaceServer.Servers;
-using static Pocket.Logger;
-
-namespace MLS.Agent.Controllers
-{
- public class LanguageServicesController : Controller
- {
- private const string CompletionRoute = "/workspace/completion";
- public static RequestDescriptor CompletionApi => new RequestDescriptor(
- CompletionRoute,
- timeoutMs: 60000,
- properties: new[]
- {
- new RequestDescriptorProperty("completionProvider"),
- });
-
- private const string DiagnosticsRoute = "/workspace/diagnostics";
- public static RequestDescriptor DiagnosticsApi => new RequestDescriptor(DiagnosticsRoute, timeoutMs: 60000);
-
- private const string SignatureHelpRoute = "/workspace/signatureHelp";
- public static RequestDescriptor SignatureHelpApi => new RequestDescriptor(SignatureHelpRoute, timeoutMs: 60000);
-
- private readonly CompositeDisposable _disposables = new CompositeDisposable();
- private readonly IWorkspaceServer _workspaceServer;
-
- public LanguageServicesController(IWorkspaceServer workspaceServer)
- {
- _workspaceServer = workspaceServer ?? throw new ArgumentNullException(nameof(workspaceServer));
- }
-
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- _disposables.Dispose();
- }
-
- base.Dispose(disposing);
- }
-
- [HttpPost]
- [Route(CompletionRoute)]
- [DebugEnableFilter]
- public async Task Completion(
- [FromBody] WorkspaceRequest request,
- [FromHeader(Name = "Timeout")] string timeoutInMilliseconds = "15000")
- {
- using (var operation = Log.OnEnterAndConfirmOnExit())
- {
- operation.Info("Processing workspaceType {workspaceType}", request.Workspace.WorkspaceType);
- if (!int.TryParse(timeoutInMilliseconds, out var timeoutMs))
- {
- return BadRequest();
- }
-
- var runTimeout = TimeSpan.FromMilliseconds(timeoutMs);
- var budget = new TimeBudget(runTimeout);
- var server = GetServerForWorkspace(request.Workspace);
- var result = await server.GetCompletionList(request, budget);
- budget.RecordEntry();
- operation.Succeed();
-
- return Ok(result);
- }
- }
-
- [HttpPost]
- [Route("/workspace/signaturehelp")]
- public async Task SignatureHelp(
- [FromBody] WorkspaceRequest request,
- [FromHeader(Name = "Timeout")] string timeoutInMilliseconds = "15000")
- {
- if (Debugger.IsAttached && !(Clock.Current is VirtualClock))
- {
- _disposables.Add(VirtualClock.Start());
- }
-
- using (var operation = Log.OnEnterAndConfirmOnExit())
- {
- operation.Info("Processing workspaceType {workspaceType}", request.Workspace.WorkspaceType);
- if (!int.TryParse(timeoutInMilliseconds, out var timeoutMs))
- {
- return BadRequest();
- }
-
- var runTimeout = TimeSpan.FromMilliseconds(timeoutMs);
- var budget = new TimeBudget(runTimeout);
- var server = GetServerForWorkspace(request.Workspace);
- var result = await server.GetSignatureHelp(request, budget);
- budget.RecordEntry();
- operation.Succeed();
-
- return Ok(result);
- }
- }
-
- [HttpPost]
- [Route(DiagnosticsRoute)]
- public async Task Diagnostics(
- [FromBody] WorkspaceRequest request,
- [FromHeader(Name = "Timeout")] string timeoutInMilliseconds = "15000")
- {
- if (Debugger.IsAttached && !(Clock.Current is VirtualClock))
- {
- _disposables.Add(VirtualClock.Start());
- }
-
- using (var operation = Log.OnEnterAndConfirmOnExit())
- {
- operation.Info("Processing workspaceType {workspaceType}", request.Workspace.WorkspaceType);
- if (!int.TryParse(timeoutInMilliseconds, out var timeoutMs))
- {
- return BadRequest();
- }
-
- var runTimeout = TimeSpan.FromMilliseconds(timeoutMs);
- var budget = new TimeBudget(runTimeout);
- var server = GetServerForWorkspace(request.Workspace);
- var result = await server.GetDiagnostics(request, budget);
- budget.RecordEntry();
- operation.Succeed();
-
- return Ok(result);
- }
- }
-
- private ILanguageService GetServerForWorkspace(Workspace workspace)
- {
- return _workspaceServer;
- }
- }
-}
diff --git a/MLS.Agent/Controllers/PackagesController.cs b/MLS.Agent/Controllers/PackagesController.cs
deleted file mode 100644
index 8b0dbb671..000000000
--- a/MLS.Agent/Controllers/PackagesController.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-// 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 Microsoft.AspNetCore.Mvc;
-using System.Threading.Tasks;
-using Microsoft.DotNet.Try.Protocol;
-using WorkspaceServer;
-using WorkspaceServer.Packaging;
-
-namespace MLS.Agent.Controllers
-{
- public class PackagesController : Controller
- {
- private const string GetPackageRoute = "/packages/{name}/{version}";
- public static RequestDescriptor GetPackageApi => new RequestDescriptor(
- GetPackageRoute,
- timeoutMs: 60000,
- method: "GET",
- templated: true);
-
- private readonly PackageRegistry _registry;
-
- public PackagesController(PackageRegistry registry)
- {
- _registry = registry;
- }
-
- [HttpGet]
- [Route(GetPackageRoute)]
- public async Task GetPackage(string name, string version)
- {
- try
- {
- var package = await _registry.Get(name);
- var isWasmSupported = package.CanSupportWasm;
- return Ok(value: new Microsoft.DotNet.Try.Protocol.Package(isWasmSupported));
- }
- catch (PackageNotFoundException ex)
- {
- return NotFound(ex.Message);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Controllers/ProjectController.cs b/MLS.Agent/Controllers/ProjectController.cs
deleted file mode 100644
index b0625dc2d..000000000
--- a/MLS.Agent/Controllers/ProjectController.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// 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.Generic;
-using Microsoft.AspNetCore.Mvc;
-using System.Linq;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.DotNet.Try.Project;
-using Microsoft.DotNet.Try.Protocol;
-using Microsoft.DotNet.Try.Protocol.ClientApi;
-using Pocket;
-using static Pocket.Logger;
-using SourceFile = Microsoft.DotNet.Try.Protocol.ClientApi.SourceFile;
-
-namespace MLS.Agent.Controllers
-{
- public class ProjectController : Controller
- {
-
- private const string RegionsFromFilesRoute = "/project/files/regions";
- public static RequestDescriptor RegionsFromFilesApi => new RequestDescriptor(RegionsFromFilesRoute, method: "POST");
-
- [HttpPost(RegionsFromFilesRoute)]
- public IActionResult GenerateRegionsFromFiles([FromBody] CreateRegionsFromFilesRequest request)
- {
- using (var operation = Log.OnEnterAndConfirmOnExit())
- {
- var regions = request.Files.SelectMany(ExtractRegions);
- var response = new CreateRegionsFromFilesResponse(request.RequestId, regions.ToArray());
-
- IActionResult result = Ok(response);
- operation.Succeed();
-
- return result;
- }
- }
-
- private static IEnumerable ExtractRegions(SourceFile sourceFile)
- {
- var sc = SourceText.From(sourceFile.Content);
- var regions = sc.ExtractRegions(sourceFile.Name).Select(
- region => new SourceFileRegion(region.bufferId.ToString(), sc.ToString(region.span).FormatSourceCode(sourceFile.Name))).ToArray();
- return regions;
- }
-
- }
-}
diff --git a/MLS.Agent/Controllers/RunController.cs b/MLS.Agent/Controllers/RunController.cs
deleted file mode 100644
index 03cb04251..000000000
--- a/MLS.Agent/Controllers/RunController.cs
+++ /dev/null
@@ -1,105 +0,0 @@
-// 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 Clockwise;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.DotNet.Try.Protocol;
-using MLS.Agent.Middleware;
-using Pocket;
-using WorkspaceServer.Models.Execution;
-using WorkspaceServer.Servers.Scripting;
-using static Pocket.Logger;
-using MLS.Agent.CommandLine;
-using WorkspaceServer.Servers;
-using WorkspaceServer.WorkspaceFeatures;
-
-namespace MLS.Agent.Controllers
-{
- public class RunController : Controller
- {
- private const string RunRoute = "/workspace/run";
- public static RequestDescriptor RunApi => new RequestDescriptor(RunRoute, timeoutMs:600000);
-
- private readonly StartupOptions _options;
- private readonly IWorkspaceServer _workspaceServer;
- private readonly CompositeDisposable _disposables = new CompositeDisposable();
-
- public RunController(
- StartupOptions options,
- IWorkspaceServer workspaceServer)
- {
- _options = options ?? throw new ArgumentNullException(nameof(options));
- _workspaceServer = workspaceServer;
- }
-
- [HttpPost]
- [Route(RunRoute)]
- [DebugEnableFilter]
- public async Task Run(
- [FromBody] WorkspaceRequest request,
- [FromHeader(Name = "Timeout")] string timeoutInMilliseconds = "45000")
- {
- if (_options.IsLanguageService)
- {
- return NotFound();
- }
-
- using (var operation = Log.OnEnterAndConfirmOnExit())
- {
- var workspaceType = request.Workspace.WorkspaceType;
-
- operation.Info("Processing workspaceType {workspaceType}", workspaceType);
-
- if (!int.TryParse(timeoutInMilliseconds, out var timeoutMs))
- {
- return BadRequest();
- }
-
- RunResult result;
- var runTimeout = TimeSpan.FromMilliseconds(timeoutMs);
-
- var budget = new TimeBudget(runTimeout);
-
- if (string.Equals(workspaceType, "script", StringComparison.OrdinalIgnoreCase))
- {
- var server = new ScriptingWorkspaceServer();
-
- result = await server.Run(
- request,
- budget);
- }
- else
- {
- using (result = await _workspaceServer.Run(request, budget))
- {
- _disposables.Add(result);
-
- if (result.Succeeded &&
- request.HttpRequest != null)
- {
- var webServer = result.GetFeature();
-
- if (webServer != null)
- {
- var response = await webServer.SendAsync(
- request.HttpRequest.ToHttpRequestMessage())
- .CancelIfExceeds(budget);
-
- result = new RunResult(
- true,
- await response.ToDisplayString());
- }
- }
- }
- }
-
- budget.RecordEntry();
- operation.Succeed();
-
- return Ok(result);
- }
- }
- }
-}
diff --git a/MLS.Agent/Controllers/SensorsController.cs b/MLS.Agent/Controllers/SensorsController.cs
deleted file mode 100644
index 762da70d7..000000000
--- a/MLS.Agent/Controllers/SensorsController.cs
+++ /dev/null
@@ -1,18 +0,0 @@
-// 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 Microsoft.AspNetCore.Mvc;
-using Microsoft.DotNet.Try.Protocol;
-using Recipes;
-
-namespace MLS.Agent.Controllers
-{
- public class SensorsController : Controller
- {
- private const string VersionRoute = "/sensors/version";
- public static RequestDescriptor VersionApi => new RequestDescriptor(VersionRoute, method: "GET");
-
- [Route(VersionRoute)]
- public IActionResult GetVersion() => Ok(VersionSensor.Version());
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Controllers/WebAssemblyController.cs b/MLS.Agent/Controllers/WebAssemblyController.cs
deleted file mode 100644
index 80e8b6786..000000000
--- a/MLS.Agent/Controllers/WebAssemblyController.cs
+++ /dev/null
@@ -1,75 +0,0 @@
-using System;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.DotNet.Try.Markdown;
-using MLS.Agent.CommandLine;
-using MLS.Agent.Tools;
-using WorkspaceServer;
-using WorkspaceServer.Packaging;
-
-namespace MLS.Agent.Controllers
-{
- public class WebAssemblyController : Controller
- {
- private PackageRegistry _registry;
-
- public WebAssemblyController(PackageRegistry packageRegistry)
- {
- _registry = packageRegistry ?? throw new ArgumentNullException(nameof(packageRegistry));
- }
-
- [HttpGet]
- [Route("/LocalCodeRunner/{packageName}/")]
- [Route("/LocalCodeRunner/{packageName}/{*requestedPath}")]
- public async Task GetFile(string packageName, string requestedPath = "Index.html")
- {
- var package = await _registry.Get(packageName);
- var asset = package.Assets.OfType().FirstOrDefault();
- if (asset == null)
- {
- return NotFound();
- }
-
- var file = asset.DirectoryAccessor.GetFullyQualifiedPath(new RelativeFilePath(requestedPath));
- if (!file.Exists)
- {
- file = asset.DirectoryAccessor.GetFullyQualifiedFilePath("index.html");
- return await FileContents(file);
- }
-
- return await FileContents(file);
- }
-
- private async Task FileContents(FileSystemInfo file)
- {
- var contentType = GetContentType(file.FullName);
- var bytes = await System.IO.File.ReadAllBytesAsync(file.FullName);
-
- return File(bytes, contentType);
- }
-
- private string GetContentType(string path)
- {
- var extension = Path.GetExtension(path);
- switch (extension)
- {
- case ".dll":
- return "application/octet-stream";
- case ".json":
- return "application/json";
- case ".wasm":
- return "application/wasm";
- case ".woff":
- return "application/font-woff";
- case ".woff2":
- return "application/font-woff";
- case ".js":
- return "application/javascript";
- default:
- return "text/html";
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Directory.Build.Props b/MLS.Agent/Directory.Build.Props
deleted file mode 100644
index 5054100f7..000000000
--- a/MLS.Agent/Directory.Build.Props
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-
- true
-
-
-
-
-
diff --git a/MLS.Agent/ExceptionExtensions.cs b/MLS.Agent/ExceptionExtensions.cs
deleted file mode 100644
index 4edff89c1..000000000
--- a/MLS.Agent/ExceptionExtensions.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-// 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 Clockwise;
-using WorkspaceServer.Servers.Scripting;
-
-namespace MLS.Agent
-{
- public static class ExceptionExtensions
- {
- public static int ToHttpStatusCode(this Exception exception)
- {
- switch (exception)
- {
- case BudgetExceededException budgetExceededException:
-
- var firstExceededEntry = budgetExceededException.Budget.Entries.FirstOrDefault(e => e.BudgetWasExceeded);
-
- if (firstExceededEntry?.Name == ScriptingWorkspaceServer.UserCodeCompletedBudgetEntryName)
- {
- return 417;
- }
-
- return 504;
-
- default:
- return 500;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/HostedService.cs b/MLS.Agent/HostedService.cs
deleted file mode 100644
index 0479bd3dd..000000000
--- a/MLS.Agent/HostedService.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-// 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;
-using System.Threading.Tasks;
-using Clockwise;
-using Microsoft.Extensions.Hosting;
-
-namespace MLS.Agent
-{
- public abstract class HostedService : IHostedService, IDisposable
- {
- private Task _executingTask;
- private Budget _budget;
-
- public Task StartAsync(CancellationToken cancellationToken)
- {
- _budget = new Budget(cancellationToken);
-
- _executingTask = ExecuteAsync(_budget);
-
- // If the task is completed then return it, otherwise it's running
- return _executingTask.IsCompleted
- ? _executingTask
- : Task.CompletedTask;
- }
-
- public async Task StopAsync(CancellationToken cancellationToken)
- {
- // Stop called without start
- if (_executingTask == null)
- {
- return;
- }
-
- _budget.Cancel();
-
- // Wait until the task completes or the stop token triggers
- await Task.WhenAny(
- _executingTask,
- Task.Delay(-1, cancellationToken));
-
- // Throw if cancellation triggered
- cancellationToken.ThrowIfCancellationRequested();
- }
-
- protected async Task ExecuteAsync()
- {
- if (_budget.IsExceeded)
- {
- return;
- }
-
- using (SchedulerContext.Establish(_budget))
- {
- await Task.Yield();
-
- await ExecuteAsync(_budget);
- }
- }
-
- protected abstract Task ExecuteAsync(Budget budget);
-
- public void Dispose() => _budget?.Cancel();
- }
-}
diff --git a/MLS.Agent/IBrowserLauncher.cs b/MLS.Agent/IBrowserLauncher.cs
deleted file mode 100644
index 3b8d2ae91..000000000
--- a/MLS.Agent/IBrowserLauncher.cs
+++ /dev/null
@@ -1,12 +0,0 @@
-// 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;
-
-namespace MLS.Agent
-{
- public interface IBrowserLauncher
- {
- void LaunchBrowser(Uri uri);
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/MLS.Agent.csproj b/MLS.Agent/MLS.Agent.csproj
deleted file mode 100644
index 679c5e457..000000000
--- a/MLS.Agent/MLS.Agent.csproj
+++ /dev/null
@@ -1,200 +0,0 @@
-
-
-
- net6.0
- Latest
- $(AssetTargetFallback);dotnet5.4;portable-net45+win8
-
-
-
- Microsoft.dotnet-try
- dotnet-try
- true
- true
- Command line tool for developers and content authors to create interactive experiences.
- dotnet interactive-programming documentation blazor interactive-tutorial csharp fsharp
- Try .NET creates interactive documentation for .NET Core.
- $(NoWarn);CS8034
- $(NoWarn);1998
- $(NoWarn);8002
- $(NoWarn);NU5129
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
- all
-
-
- all
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- PreserveNewest
-
-
-
-
-
-
- MLS.Agent.Program.cs
-
-
- demo.zip
-
-
-
-
-
-
-
-
-
-
-
- $(MSBuildThisFileDirectory)wwwroot
- $(MSBuildThisFileDirectory)../Microsoft.DotNet.Try.Client
- $(webRootDir)/client
- $(ClientOutputDir)/bundle.js
- $(MSBuildThisFileDirectory)../Microsoft.DotNet.Try.js
- $(webRootDir)/api
- $(TryDotNetJsOutputDir)/trydotnet.min.js
- $(TryDotNetJsOutputDir)/trydotnet.min.js.map
- $(MSBuildThisFileDirectory)../Microsoft.DotNet.Try.Styles
- $(webRootDir)/css
- $(CssOutputDir)/trydotnet.css
-
-
-
-
-
-
-
-
-
-
-
- <_TryDotNetCssExists Condition="Exists('$(CssOutputFile)')">true
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- <_TryDotNetMinJsExists Condition="Exists('$(TryDotNetJsFile)')">true
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- <_TryDotNetClientExists Condition="Exists('$(ClientOutputFile)')">true
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- PreserveNewest
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/MLS.Agent/MLS.Agent.v3.ncrunchproject b/MLS.Agent/MLS.Agent.v3.ncrunchproject
deleted file mode 100644
index fd18d4092..000000000
--- a/MLS.Agent/MLS.Agent.v3.ncrunchproject
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
- ..\docs\**.*
- wwwroot\**.*
- ..\Microsoft.DotNet.Interactive.Jupyter\ContentFiles\**.*
-
-
-
-
\ No newline at end of file
diff --git a/MLS.Agent/Markdown/AnnotatedCodeBlockExtensions.cs b/MLS.Agent/Markdown/AnnotatedCodeBlockExtensions.cs
deleted file mode 100644
index 6b773e6d9..000000000
--- a/MLS.Agent/Markdown/AnnotatedCodeBlockExtensions.cs
+++ /dev/null
@@ -1,52 +0,0 @@
-// 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 Microsoft.DotNet.Try.Markdown;
-using Microsoft.DotNet.Try.Protocol;
-using MLS.Agent.Tools;
-using Buffer = Microsoft.DotNet.Try.Protocol.Buffer;
-
-namespace MLS.Agent.Markdown
-{
- public static class AnnotatedCodeBlockExtensions
- {
- public static Buffer GetBufferAsync(
- this AnnotatedCodeBlock block,
- IDirectoryAccessor directoryAccessor)
- {
- if (block.Annotations is LocalCodeBlockAnnotations localOptions)
- {
- var file = localOptions.SourceFile ?? localOptions.DestinationFile;
- var absolutePath = directoryAccessor.GetFullyQualifiedPath(file).FullName;
- var bufferId = new BufferId(absolutePath, localOptions.Region);
- return new Buffer(bufferId, block.SourceCode);
- }
-
- return null;
- }
-
- public static string ProjectOrPackageName(this AnnotatedCodeBlock block)
- {
- if (block.Annotations is LocalCodeBlockAnnotations a1 &&
- a1.Project?.FullName is { } fullName)
- {
- return fullName;
- }
-
- if (block.Annotations is CodeBlockAnnotations a2)
- {
- return a2.Package;
- }
-
- return null;
- }
-
- public static string PackageName(this AnnotatedCodeBlock block)
- {
- return (block.Annotations as CodeBlockAnnotations)?.Package;
- }
-
- public static string Language(this AnnotatedCodeBlock block) => block.Annotations?.NormalizedLanguage;
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Markdown/LocalCodeBlockAnnotations.cs b/MLS.Agent/Markdown/LocalCodeBlockAnnotations.cs
deleted file mode 100644
index 53a661719..000000000
--- a/MLS.Agent/Markdown/LocalCodeBlockAnnotations.cs
+++ /dev/null
@@ -1,187 +0,0 @@
-// 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.CommandLine.Parsing;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.Text;
-using Microsoft.DotNet.Try.Markdown;
-using Microsoft.DotNet.Try.Project;
-using MLS.Agent.Tools;
-using WorkspaceServer;
-using WorkspaceServer.Packaging;
-
-namespace MLS.Agent.Markdown
-{
- public class LocalCodeBlockAnnotations : CodeBlockAnnotations
- {
- public LocalCodeBlockAnnotations(
- RelativeFilePath sourceFile = null,
- RelativeFilePath destinationFile = null,
- FileInfo project = null,
- string package = null,
- string region = null,
- string session = null,
- bool isProjectFileImplicit = false,
- bool editable = false,
- bool hidden = false,
- string runArgs = null,
- ParseResult parseResult = null,
- string packageVersion = null) : base(destinationFile, package, region, session, editable, hidden, runArgs, parseResult ,packageVersion)
- {
- SourceFile = sourceFile;
- Project = project;
- IsProjectImplicit = isProjectFileImplicit;
- }
-
- public FileInfo Project { get; }
-
- public override string Package => base.Package ?? Project?.FullName;
-
- public RelativeFilePath SourceFile { get; }
-
- public bool IsProjectImplicit { get; set; }
-
- public IDirectoryAccessor MarkdownProjectRoot { get; internal set; }
-
- internal PackageRegistry PackageRegistry { get; set; }
-
- public override async Task TryGetExternalContent()
- {
- string content = null;
-
- var errors = new List();
-
- await Validate(errors);
-
- if (!errors.Any())
- {
- if (SourceFile == null)
- {
- return CodeBlockContentFetchResult.None;
- }
-
- content = MarkdownProjectRoot.ReadAllText(SourceFile);
-
- if (string.IsNullOrWhiteSpace(Region))
- {
- return errors.Any()
- ? CodeBlockContentFetchResult.Failed(errors)
- : CodeBlockContentFetchResult.Succeeded(content);
- }
-
- var sourceText = SourceText.From(content);
- var sourceFileAbsolutePath = GetSourceFileAbsolutePath();
-
- var buffers = sourceText.ExtractBuffers(sourceFileAbsolutePath)
- .Where(b => b.Id.RegionName == Region)
- .ToArray();
-
- if (buffers.Length == 0)
- {
- errors.Add($"Region \"{Region}\" not found in file {sourceFileAbsolutePath}");
- }
- else if (buffers.Length > 1)
- {
- errors.Add($"Multiple regions found: {Region}");
- }
- else
- {
- content = buffers[0].Content;
- }
- }
-
- return errors.Any()
- ? CodeBlockContentFetchResult.Failed(errors)
- : CodeBlockContentFetchResult.Succeeded(content);
- }
-
- private async Task Validate(List errors)
- {
- if (SourceFile != null && !MarkdownProjectRoot.FileExists(SourceFile))
- {
- errors.Add($"File not found: {SourceFile.Value}");
- }
-
- if (string.IsNullOrEmpty(Package) && Project == null)
- {
- errors.Add("No project file or package specified");
- }
-
- if (Package != null)
- {
- try
- {
- var package = await PackageRegistry.Find(Package);
- }
- catch (PackageNotFoundException e)
- {
- errors.Add(e.Message);
- return;
- }
- }
-
- if (Project != null)
- {
- var packageName = GetPackageNameFromProjectFile(Project);
-
- if (packageName == null)
- {
- errors.Add($"No project file could be found at path {MarkdownProjectRoot.GetFullyQualifiedPath(new RelativeDirectoryPath("."))}");
- }
- }
- }
-
- public override async Task AddAttributes(AnnotatedCodeBlock block)
- {
- if (Package == null && Project?.FullName != null)
- {
- block.AddAttribute("data-trydotnet-package", Project.FullName);
- }
-
- var fileName = GetDestinationFileAbsolutePath();
-
- if (!string.IsNullOrWhiteSpace(fileName))
- {
- block.AddAttribute(
- "data-trydotnet-file-name",
- fileName);
- }
-
- if (ReadOnlyRegionRoundtrip())
- {
- block.AddAttribute("data-trydotnet-injection-point", "replace");
- }
-
- bool ReadOnlyRegionRoundtrip()
- {
- return !Editable && !string.IsNullOrWhiteSpace(Region) && SourceFile != null && (DestinationFile == null || SourceFile.Equals(DestinationFile));
- }
-
- await base.AddAttributes(block);
- }
-
- private string GetDestinationFileAbsolutePath()
- {
- var file = DestinationFile ?? SourceFile;
- return file == null
- ? string.Empty
- : MarkdownProjectRoot
- .GetFullyQualifiedPath(file)
- .FullName;
- }
-
- private static string GetPackageNameFromProjectFile(FileInfo projectFile)
- {
- return projectFile?.FullName;
- }
-
- private string GetSourceFileAbsolutePath()
- {
- return MarkdownProjectRoot.GetFullyQualifiedPath(SourceFile).FullName;
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Markdown/LocalCodeFenceAnnotationsParser.cs b/MLS.Agent/Markdown/LocalCodeFenceAnnotationsParser.cs
deleted file mode 100644
index 923a8b1c9..000000000
--- a/MLS.Agent/Markdown/LocalCodeFenceAnnotationsParser.cs
+++ /dev/null
@@ -1,157 +0,0 @@
-// 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.CommandLine;
-using System.IO;
-using System.Linq;
-using Markdig;
-using Microsoft.DotNet.Try.Markdown;
-using MLS.Agent.Tools;
-using WorkspaceServer;
-
-namespace MLS.Agent.Markdown
-{
- public class LocalCodeFenceAnnotationsParser : CodeFenceAnnotationsParser
- {
- private readonly IDirectoryAccessor _directoryAccessor;
- private readonly PackageRegistry _packageRegistry;
-
- public LocalCodeFenceAnnotationsParser(
- IDirectoryAccessor directoryAccessor,
- PackageRegistry packageRegistry,
- IDefaultCodeBlockAnnotations defaultAnnotations = null) : base(defaultAnnotations,
- csharp =>
- {
- AddCsharpProjectOption(csharp, directoryAccessor);
- AddSourceFileOption(csharp);
- },
- fsharp =>
- {
- AddFsharpProjectOption(fsharp, directoryAccessor);
- AddSourceFileOption(fsharp);
- })
- {
- _directoryAccessor = directoryAccessor;
- _packageRegistry = packageRegistry ?? throw new ArgumentNullException(nameof(packageRegistry));
- }
-
- public override CodeFenceOptionsParseResult TryParseCodeFenceOptions(
- string line,
- MarkdownParserContext context = null)
- {
- var result = base.TryParseCodeFenceOptions(line, context);
-
- if (result is SuccessfulCodeFenceOptionParseResult succeeded &&
- succeeded.Annotations is LocalCodeBlockAnnotations local)
- {
- local.MarkdownProjectRoot = _directoryAccessor;
- local.PackageRegistry = _packageRegistry;
-
- var projectResult = local.ParseResult.CommandResult["project"];
- if (projectResult?.IsImplicit ?? false)
- {
- local.IsProjectImplicit = true;
- }
- }
-
- return result;
- }
-
- public override Type CodeBlockAnnotationsType => typeof(LocalCodeBlockAnnotations);
-
- private static void AddSourceFileOption(Command command)
- {
- var sourceFileArg = new Argument(
- parse: result =>
- {
- var filename = result.Tokens.Select(t => t.Value).SingleOrDefault();
-
- if (filename == null)
- {
- return null;
- }
-
- if (RelativeFilePath.TryParse(filename, out var relativeFilePath))
- {
- return relativeFilePath;
- }
-
- result.ErrorMessage = $"Error parsing the filename: {filename}";
- return null;
- })
- {
- Name = "SourceFile",
- Arity = ArgumentArity.ZeroOrOne
- };
-
- var sourceFileOption = new Option("--source-file")
- {
- Argument = sourceFileArg
- };
-
- command.AddOption(sourceFileOption);
- }
-
- private static void AddCsharpProjectOption(
- Command command,
- IDirectoryAccessor directoryAccessor)
- {
- AddProjectOption(command, directoryAccessor, ".csproj");
- }
-
- private static void AddFsharpProjectOption(
- Command command,
- IDirectoryAccessor directoryAccessor)
- {
- AddProjectOption(command,directoryAccessor, ".fsproj");
- }
-
- private static void AddProjectOption(
- Command command,
- IDirectoryAccessor directoryAccessor,
- string projectFileExtension)
- {
- var projectOptionArgument = new Argument(
- parse: (result) =>
- {
- var projectPath = new RelativeFilePath(result.Tokens.Select(t => t.Value).Single());
-
- if (directoryAccessor.FileExists(projectPath))
- {
- return directoryAccessor.GetFullyQualifiedFilePath(projectPath);
- }
-
- result.ErrorMessage = $"Project not found: {projectPath.Value}";
- return null;
- })
-
- {
- Name = "project",
- Arity = ArgumentArity.ExactlyOne
- };
-
- projectOptionArgument.SetDefaultValueFactory(() =>
- {
- var rootDirectory = directoryAccessor.GetFullyQualifiedPath(new RelativeDirectoryPath("."));
- var projectFiles = directoryAccessor.GetAllFilesRecursively()
- .Where(file => directoryAccessor.GetFullyQualifiedPath(file.Directory).FullName == rootDirectory.FullName && file.Extension == projectFileExtension)
- .ToArray();
-
- if (projectFiles.Length == 1)
- {
- return directoryAccessor.GetFullyQualifiedPath(projectFiles.Single());
- }
-
- return null;
- });
-
- var projectOption = new Option("--project")
- {
- Argument = projectOptionArgument
- };
-
- command.Add(projectOption);
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Markdown/MarkdownFile.cs b/MLS.Agent/Markdown/MarkdownFile.cs
deleted file mode 100644
index ca9e5e1ba..000000000
--- a/MLS.Agent/Markdown/MarkdownFile.cs
+++ /dev/null
@@ -1,163 +0,0 @@
-// 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.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Html;
-using Microsoft.DotNet.Try.Markdown;
-using Microsoft.DotNet.Try.Protocol;
-using MLS.Agent.Tools;
-using Buffer = Microsoft.DotNet.Try.Protocol.Buffer;
-
-namespace MLS.Agent.Markdown
-{
- public class MarkdownFile
- {
- public MarkdownFile(
- RelativeFilePath path,
- MarkdownProject project)
- {
- Path = path;
- Project = project;
- }
-
- public RelativeFilePath Path { get; }
-
- public MarkdownProject Project { get; }
-
- public async Task> GetAnnotatedCodeBlocks()
- {
- var pipeline = Project.GetMarkdownPipelineFor(Path);
-
- var document = Markdig.Markdown.Parse(
- ReadAllText(),
- pipeline);
-
- var blocks = document
- .OfType()
- .OrderBy(c => c.Order)
- .ToArray();
-
- await Task.WhenAll(blocks.Select(b => b.InitializeAsync()));
-
- return blocks;
- }
-
- public async Task> GetEditableAnnotatedCodeBlocks() =>
- (await GetAnnotatedCodeBlocks())
- .Where(b => b.Annotations is CodeBlockAnnotations a &&
- a.Editable)
- .ToArray();
-
- public async Task> GetNonEditableAnnotatedCodeBlocks() =>
- (await GetAnnotatedCodeBlocks())
- .Where(b => b.Annotations is CodeBlockAnnotations a &&
- !a.Editable)
- .ToArray();
-
- public async Task> GetSessions() =>
- (await GetAnnotatedCodeBlocks())
- .GroupBy(block => block.Annotations?.Session)
- .Select(grouping => new Session(grouping.Key, grouping.ToArray(), this))
- .ToArray();
-
- public async Task ToHtmlContentAsync()
- {
- var pipeline = Project.GetMarkdownPipelineFor(Path);
- var html = await pipeline.RenderHtmlAsync(ReadAllText());
- return new HtmlString(html);
- }
-
- public string ReadAllText() =>
- Project.DirectoryAccessor.ReadAllText(Path);
-
- internal async Task<(Dictionary buffers, Dictionary files)> GetIncludes(IDirectoryAccessor directoryAccessor)
- {
- var buffersToIncludeBySession = new Dictionary(StringComparer.InvariantCultureIgnoreCase);
-
- var contentBuildersByBufferBySession = new Dictionary>(StringComparer.InvariantCultureIgnoreCase);
-
- var filesToIncludeBySession = new Dictionary(StringComparer.InvariantCultureIgnoreCase);
-
- var contentBuildersByFileBySession = new Dictionary>(StringComparer.InvariantCultureIgnoreCase);
-
- var blocks = await GetNonEditableAnnotatedCodeBlocks();
-
- foreach (var block in blocks)
- {
- if (!(block.Annotations is CodeBlockAnnotations annotations))
- {
- continue;
- }
-
- var sessionId = string.IsNullOrWhiteSpace(block.Annotations.Session)
- ? "global"
- : block.Annotations.Session;
-
- var filePath = (block.Annotations as LocalCodeBlockAnnotations)?.SourceFile ??
- annotations.DestinationFile ??
- new RelativeFilePath($"./generated_include_file_{sessionId}.cs");
-
- var absolutePath = directoryAccessor.GetFullyQualifiedPath(filePath).FullName;
-
- if (string.IsNullOrWhiteSpace(annotations.Region))
- {
- if (!contentBuildersByFileBySession.TryGetValue(sessionId, out var sessionFileBuffers))
- {
- sessionFileBuffers = new Dictionary(StringComparer.InvariantCultureIgnoreCase);
- contentBuildersByFileBySession[sessionId] = sessionFileBuffers;
- }
-
- if (!sessionFileBuffers.TryGetValue(absolutePath, out var fileBuffer))
- {
- fileBuffer = new StringBuilder();
- sessionFileBuffers[absolutePath] = fileBuffer;
- }
-
- fileBuffer.AppendLine(block.SourceCode);
- }
- else
- {
- var bufferId = new BufferId(absolutePath, annotations.Region);
- if (!contentBuildersByBufferBySession.TryGetValue(sessionId, out var sessionFileBuffers))
- {
- sessionFileBuffers = new Dictionary();
- contentBuildersByBufferBySession[sessionId] = sessionFileBuffers;
- }
-
- if (!sessionFileBuffers.TryGetValue(bufferId, out var bufferContentBuilder))
- {
- bufferContentBuilder = new StringBuilder();
- sessionFileBuffers[bufferId] = bufferContentBuilder;
- }
-
- bufferContentBuilder.AppendLine(block.SourceCode);
- }
- }
-
- foreach (var (sessionId, contentBuildersByBuffer) in contentBuildersByBufferBySession)
- {
- buffersToIncludeBySession[sessionId] = contentBuildersByBuffer
- .Select(contentBuilder => new Buffer(
- contentBuilder.Key,
- contentBuilder.Value.ToString())
- ).ToArray();
- }
-
- foreach (var (sessionId, contentBuildersByFile) in contentBuildersByFileBySession)
- {
- filesToIncludeBySession[sessionId] = contentBuildersByFile
- .Select(fileBuffer => new File(
- fileBuffer.Key,
- fileBuffer.Value.ToString()
- )
- ).ToArray();
- }
-
- return (buffersToIncludeBySession, filesToIncludeBySession);
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Markdown/MarkdownPipelineBuilderExtensions.cs b/MLS.Agent/Markdown/MarkdownPipelineBuilderExtensions.cs
deleted file mode 100644
index bf019a2e4..000000000
--- a/MLS.Agent/Markdown/MarkdownPipelineBuilderExtensions.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// 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 Markdig;
-using Microsoft.DotNet.Try.Markdown;
-using MLS.Agent.Tools;
-using WorkspaceServer;
-
-namespace MLS.Agent.Markdown
-{
- public static class MarkdownPipelineBuilderExtensions
- {
- public static MarkdownPipelineBuilder UseCodeBlockAnnotations(
- this MarkdownPipelineBuilder pipeline,
- IDirectoryAccessor directoryAccessor,
- PackageRegistry packageRegistry,
- IDefaultCodeBlockAnnotations defaultAnnotations = null)
- {
- return pipeline.UseCodeBlockAnnotations(
- new LocalCodeFenceAnnotationsParser(
- directoryAccessor,
- packageRegistry,
- defaultAnnotations));
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Markdown/MarkdownPipelineExtensions.cs b/MLS.Agent/Markdown/MarkdownPipelineExtensions.cs
deleted file mode 100644
index 10672b0cd..000000000
--- a/MLS.Agent/Markdown/MarkdownPipelineExtensions.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// 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 Markdig;
-using Markdig.Renderers;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.DotNet.Try.Markdown;
-
-namespace MLS.Agent.Markdown
-{
- public static class MarkdownPipelineExtensions
- {
- public static async Task RenderHtmlAsync(this MarkdownPipeline pipeline, string text)
- {
- var document = Markdig.Markdown.Parse(
- text,
- pipeline);
-
- var initializeTasks = document.OfType()
- .Select(c => c.InitializeAsync());
-
- await Task.WhenAll(initializeTasks);
-
- using (var writer = new StringWriter())
- {
- var renderer = new HtmlRenderer(writer);
- pipeline.Setup(renderer);
- renderer.Render(document);
- var html = writer.ToString();
- return html;
- }
- }
- }
-}
diff --git a/MLS.Agent/Markdown/MarkdownProject.cs b/MLS.Agent/Markdown/MarkdownProject.cs
deleted file mode 100644
index 42ed333b7..000000000
--- a/MLS.Agent/Markdown/MarkdownProject.cs
+++ /dev/null
@@ -1,125 +0,0 @@
-// Copyright (c) .NET Foundation and contributors. All rights reserved.
-// Licensed under the MIT license. See LICENSE file in the project root for full license information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using Markdig;
-using Microsoft.DotNet.Try.Markdown;
-using MLS.Agent.Tools;
-using Recipes;
-using WorkspaceServer;
-
-namespace MLS.Agent.Markdown
-{
- public class MarkdownProject
- {
- private readonly PackageRegistry _packageRegistry;
-
- private readonly Dictionary _markdownPipelines = new Dictionary();
-
- private readonly IDefaultCodeBlockAnnotations _defaultAnnotations;
-
- internal MarkdownProject(PackageRegistry packageRegistry) : this(new NullDirectoryAccessor(), packageRegistry)
- {
- }
-
- public MarkdownProject(
- IDirectoryAccessor directoryAccessor,
- PackageRegistry packageRegistry,
- IDefaultCodeBlockAnnotations defaultAnnotations = null)
- {
- DirectoryAccessor = directoryAccessor ?? throw new ArgumentNullException(nameof(directoryAccessor));
- _packageRegistry = packageRegistry ?? throw new ArgumentNullException(nameof(packageRegistry));
- _defaultAnnotations = defaultAnnotations;
- }
-
- internal IDirectoryAccessor DirectoryAccessor { get; }
-
- public IReadOnlyCollection GetAllMarkdownFiles() =>
- Enumerable.Where(DirectoryAccessor.GetAllFilesRecursively(), file => file.Extension == ".md")
- .Select(file => new MarkdownFile(file, this))
- .ToArray();
-
- public bool TryGetMarkdownFile(RelativeFilePath path, out MarkdownFile markdownFile)
- {
- if (!DirectoryAccessor.FileExists(path) || path.Extension != ".md")
- {
- markdownFile = null;
- return false;
- }
-
- markdownFile = new MarkdownFile(path, this);
- return true;
- }
-
- internal MarkdownPipeline GetMarkdownPipelineFor(RelativeFilePath filePath)
- {
- return _markdownPipelines.GetOrAdd(filePath, key =>
- {
- var relativeAccessor = DirectoryAccessor.GetDirectoryAccessorForRelativePath(filePath.Directory);
-
- return new MarkdownPipelineBuilder()
- .UseCodeBlockAnnotations(
- relativeAccessor,
- _packageRegistry,
- _defaultAnnotations)
- .UseMathematics()
- .UseAdvancedExtensions()
- .Build();
- });
- }
-
- private class NullDirectoryAccessor : IDirectoryAccessor
- {
- public bool DirectoryExists(RelativeDirectoryPath path)
- {
- return false;
- }
-
- public void EnsureDirectoryExists(RelativeDirectoryPath path)
- {
- }
-
- public bool FileExists(RelativeFilePath filePath)
- {
- return false;
- }
-
- public string ReadAllText(RelativeFilePath filePath)
- {
- return string.Empty;
- }
-
- public IEnumerable GetAllFilesRecursively()
- {
- return Enumerable.Empty();
- }
-
- public IEnumerable GetAllFiles()
- {
- return Enumerable.Empty();
- }
-
- public IEnumerable GetAllDirectoriesRecursively()
- {
- return Enumerable.Empty();
- }
-
- public FileSystemInfo GetFullyQualifiedPath(RelativePath path)
- {
- return null;
- }
-
- public IDirectoryAccessor GetDirectoryAccessorForRelativePath(RelativeDirectoryPath relativePath)
- {
- return this;
- }
-
- public void WriteAllText(RelativeFilePath path, string text)
- {
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Markdown/Session.cs b/MLS.Agent/Markdown/Session.cs
deleted file mode 100644
index 460bc2d03..000000000
--- a/MLS.Agent/Markdown/Session.cs
+++ /dev/null
@@ -1,132 +0,0 @@
-// 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.Linq;
-using System.Threading.Tasks;
-using Microsoft.DotNet.Try.Markdown;
-using Microsoft.DotNet.Try.Project;
-using Microsoft.DotNet.Try.Protocol;
-using WorkspaceServer;
-
-namespace MLS.Agent.Markdown
-{
- public class Session
- {
- internal Session(
- string name,
- IReadOnlyCollection codeBlocks,
- MarkdownFile markdownFile)
- {
- Name = name;
- CodeBlocks = codeBlocks;
- MarkdownFile = markdownFile;
-
- var projectOrPackageNames = codeBlocks
- .Select(block => block.ProjectOrPackageName())
- .Distinct()
- .ToArray();
-
- if (projectOrPackageNames.Length == 1)
- {
- ProjectOrPackageName = projectOrPackageNames[0];
- }
- else
- {
- ProjectOrPackageName = projectOrPackageNames.FirstOrDefault();
- }
-
- Language = CodeBlocks
- .Select(b => b.Language())
- .FirstOrDefault(n => !string.IsNullOrWhiteSpace(n));
- }
-
- public string Language { get; }
-
- public string Name { get; }
-
- public IReadOnlyCollection CodeBlocks { get; }
-
- public MarkdownFile MarkdownFile { get; }
-
- public string ProjectOrPackageName { get; }
-
- public async Task GetWorkspaceAsync()
- {
- var (buffersToInclude, filesToInclude) = await MarkdownFile.GetIncludes(MarkdownFile.Project.DirectoryAccessor);
-
- var markdownFileDir = MarkdownFile.Project.DirectoryAccessor.GetDirectoryAccessorForRelativePath(MarkdownFile.Path.Directory);
-
- var buffers = CodeBlocks
- .Where(b => b.Annotations is CodeBlockAnnotations a && a.Editable)
- .Select(block => block.GetBufferAsync(markdownFileDir))
- .ToList();
-
- var files = new List();
-
- if (filesToInclude.TryGetValue("global", out var globalIncludes))
- {
- files.AddRange(globalIncludes);
- }
-
- if (!string.IsNullOrWhiteSpace(Name) && filesToInclude.TryGetValue(Name, out var sessionIncludes))
- {
- files.AddRange(sessionIncludes);
- }
-
- if (buffersToInclude.TryGetValue("global", out var globalSessionBuffersToInclude))
- {
- buffers.AddRange(globalSessionBuffersToInclude);
- }
-
- if (!string.IsNullOrWhiteSpace(Name) && buffersToInclude.TryGetValue(Name, out var localSessionBuffersToInclude))
- {
- buffers.AddRange(localSessionBuffersToInclude);
- }
-
- var workspace = new Workspace(
- workspaceType: ProjectOrPackageName,
- language: Language,
- files: files.ToArray(),
- buffers: buffers.ToArray());
-
- workspace = await workspace
- .MergeAsync()
- .InlineBuffersAsync();
-
- return workspace;
- }
-
- internal bool IsProjectCompatibleWithLanguage
- {
- get
- {
- var projectOrPackage = new UriOrFileInfo(ProjectOrPackageName);
-
- var supported = true;
-
- if (projectOrPackage.IsFile)
- {
- var extension = projectOrPackage.FileExtension.ToLowerInvariant();
- switch (extension.ToLowerInvariant())
- {
- case ".csproj":
- supported = StringComparer.OrdinalIgnoreCase.Compare(Language, "csharp") == 0;
- break;
-
- case ".fsproj":
- supported = StringComparer.OrdinalIgnoreCase.Compare(Language, "fsharp") == 0;
- break;
-
- default:
- supported = false;
- break;
- }
- }
-
- return supported;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Middleware/DebugEnableFilterAttribute.cs b/MLS.Agent/Middleware/DebugEnableFilterAttribute.cs
deleted file mode 100644
index e4ca44acb..000000000
--- a/MLS.Agent/Middleware/DebugEnableFilterAttribute.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// 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.Diagnostics;
-using Clockwise;
-using Microsoft.AspNetCore.Mvc.Filters;
-using Pocket;
-
-namespace MLS.Agent.Middleware
-{
- public class DebugEnableFilterAttribute : ActionFilterAttribute
- {
- private readonly CompositeDisposable _disposables = new CompositeDisposable();
-
- public override void OnActionExecuting(ActionExecutingContext context)
- {
- if (Debugger.IsAttached && !(Clock.Current is VirtualClock))
- {
- _disposables.Add(VirtualClock.Start());
- }
- }
-
- public override void OnActionExecuted(ActionExecutedContext context)
- {
- _disposables.Dispose();
- }
- }
-}
-
diff --git a/MLS.Agent/Middleware/ExceptionFilter.cs b/MLS.Agent/Middleware/ExceptionFilter.cs
deleted file mode 100644
index 1a4c9209e..000000000
--- a/MLS.Agent/Middleware/ExceptionFilter.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-// 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.AspNetCore.Mvc;
-using Microsoft.AspNetCore.Mvc.Filters;
-using Pocket;
-using static Pocket.Logger;
-
-namespace MLS.Agent.Middleware
-{
- public class ExceptionFilter : IExceptionFilter
- {
- public void OnException(ExceptionContext context)
- {
- var exception = context.Exception;
-
- if (exception == null)
- {
- return;
- }
-
- if (context.ModelState.ErrorCount > 0)
- {
- context.Result = new BadRequestResult();
- }
- else
- {
- context.Result = new ExceptionResult(exception);
-
- if (context.ExceptionHandled)
- {
- Log.Warning(exception);
- }
- else
- {
- Log.Error(exception);
- }
- }
- }
-
- private class ExceptionResult : IActionResult
- {
- private readonly Exception exception;
-
- public ExceptionResult(Exception exception)
- {
- this.exception = exception;
- }
-
- public async Task ExecuteResultAsync(ActionContext context)
- {
- var objectResult = new ObjectResult(new
- {
- message = "An unhandled exception occurred.",
- exception = exception.ToString()
- })
- {
- StatusCode = exception.ToHttpStatusCode()
- };
-
- await objectResult.ExecuteResultAsync(context);
- }
- }
- }
-}
diff --git a/MLS.Agent/Program.cs b/MLS.Agent/Program.cs
deleted file mode 100644
index 9b14c220a..000000000
--- a/MLS.Agent/Program.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-// 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 Microsoft.ApplicationInsights;
-using Microsoft.ApplicationInsights.Extensibility;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.DependencyInjection;
-using MLS.Agent.Tools;
-using Pocket;
-using Pocket.For.ApplicationInsights;
-using Recipes;
-using Serilog.Sinks.RollingFileAlternate;
-using System;
-using System.CommandLine.Parsing;
-using System.IO;
-using System.Reflection;
-using System.Security.Cryptography.X509Certificates;
-using System.Text;
-using System.Threading.Tasks;
-using static Pocket.Logger;
-using SerilogLoggerConfiguration = Serilog.LoggerConfiguration;
-using MLS.Agent.CommandLine;
-using WorkspaceServer.Servers;
-
-namespace MLS.Agent
-{
- public class Program
- {
- private static readonly ServiceCollection _serviceCollection = new ServiceCollection();
-
- public static async Task Main(string[] args)
- {
- Console.OutputEncoding = Encoding.UTF8;
-
- return await CommandLineParser.Create( _serviceCollection ).InvokeAsync(args);
- }
-
- public static X509Certificate2 ParseKey(string base64EncodedKey)
- {
- var bytes = Convert.FromBase64String(base64EncodedKey);
- return new X509Certificate2(bytes);
- }
-
- private static readonly Assembly[] _assembliesEmittingPocketLoggerLogs = {
- typeof(Startup).Assembly,
- typeof(AsyncLazy<>).Assembly,
- typeof(IWorkspaceServer).Assembly
- };
-
- private static IDisposable StartAppInsightsLogging(StartupOptions options)
- {
-
- var disposables = new CompositeDisposable();
-
- if (options.Production)
- {
- var applicationVersion = VersionSensor.Version().AssemblyInformationalVersion;
- var websiteSiteName = Environment.GetEnvironmentVariable("WEBSITE_SITE_NAME") ?? "UNKNOWN-AGENT";
- var regionId = options.RegionId ?? "undefined";
- disposables.Add(
- LogEvents.Enrich(a =>
- {
- a(("regionId", regionId));
- a(("applicationVersion", applicationVersion));
- a(("websiteSiteName", websiteSiteName));
- a(("id", options.Id));
- }));
- }
-
- if (options.ApplicationInsightsKey != null)
- {
- var telemetryClient = new TelemetryClient(new TelemetryConfiguration(options.ApplicationInsightsKey))
- {
- InstrumentationKey = options.ApplicationInsightsKey
- };
- disposables.Add(telemetryClient.SubscribeToPocketLogger(_assembliesEmittingPocketLoggerLogs));
- }
-
- Log.Event("AgentStarting");
-
- return disposables;
- }
-
- internal static IDisposable StartToolLogging(StartupOptions options)
- {
- var disposables = new CompositeDisposable();
-
- if (options.LogPath != null)
- {
- var log = new SerilogLoggerConfiguration()
- .WriteTo
- .RollingFileAlternate(options.LogPath.FullName, outputTemplate: "{Message}{NewLine}")
- .CreateLogger();
-
- var subscription = LogEvents.Subscribe(
- e => log.Information(e.ToLogString()),
- _assembliesEmittingPocketLoggerLogs);
-
- disposables.Add(subscription);
- disposables.Add(log);
- }
-
- if (options.Verbose)
- {
- disposables.Add(
- LogEvents.Subscribe(e => Console.WriteLine(e.ToLogString()),
- _assembliesEmittingPocketLoggerLogs));
- }
-
- TaskScheduler.UnobservedTaskException += (sender, args) =>
- {
- Log.Warning($"{nameof(TaskScheduler.UnobservedTaskException)}", args.Exception);
- args.SetObserved();
- };
-
- return disposables;
- }
-
- public static IWebHost ConstructWebHost(StartupOptions options)
- {
- var disposables = new CompositeDisposable
- {
- StartAppInsightsLogging(options),
- StartToolLogging(options)
- };
-
- if (options.Key is null)
- {
- Log.Trace("No Key Provided");
- }
- else
- {
- Log.Trace("Received Key: {key}", options.Key);
- }
-
- var webHost = new WebHostBuilder()
- .UseKestrel()
- .UseContentRoot(Path.GetDirectoryName(typeof(Program).Assembly.Location))
- .ConfigureServices(c =>
- {
- if (!string.IsNullOrEmpty(options.ApplicationInsightsKey))
- {
- c.AddApplicationInsightsTelemetry(options.ApplicationInsightsKey);
- }
-
- c.AddSingleton(options);
-
- foreach (var serviceDescriptor in _serviceCollection)
- {
- c.Add(serviceDescriptor);
- }
- })
- .UseEnvironment(options.EnvironmentName)
- .UseStartup()
- .ConfigureUrl(options.Mode, options.Port)
- .Build();
-
- return webHost;
- }
- }
-}
diff --git a/MLS.Agent/Properties/launchSettings.json b/MLS.Agent/Properties/launchSettings.json
deleted file mode 100644
index 6c5badbb6..000000000
--- a/MLS.Agent/Properties/launchSettings.json
+++ /dev/null
@@ -1,46 +0,0 @@
-{
- "iisSettings": {
- "windowsAuthentication": false,
- "anonymousAuthentication": true,
- "iisExpress": {
- "applicationUrl": "http://localhost:4242/",
- "sslPort": 0
- }
- },
- "profiles": {
- "IIS Express": {
- "commandName": "IISExpress",
- "commandLineArgs": "--port 4242 hosted",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
- },
- "Try": {
- "commandName": "Project",
- "commandLineArgs": "--port 4242 ../Samples ",
- "launchBrowser": true,
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
- },
- "Hosted": {
- "commandName": "Project",
- "commandLineArgs": "--port 4242 hosted ",
- "environmentVariables": {
- "ASPNETCORE_ENVIRONMENT": "Development"
- }
- },
- "Jupyter": {
- "commandName": "Project",
- "commandLineArgs": "../MLS.Agent.Tests/kernel_connection_file.json"
- },
- "Verify": {
- "commandName": "Project",
- "commandLineArgs": "verify \"..\\Samples\""
- },
- "Publish": {
- "commandName": "Project",
- "commandLineArgs": "publish \"..\\Samples\" --format Markdown --target-directory \"..\\Samples\\published\""
- }
- }
-}
\ No newline at end of file
diff --git a/MLS.Agent/Startup.cs b/MLS.Agent/Startup.cs
deleted file mode 100644
index a984e6ed9..000000000
--- a/MLS.Agent/Startup.cs
+++ /dev/null
@@ -1,247 +0,0 @@
-// 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.IO;
-using System.Linq;
-using System.Net;
-using System.Net.Mime;
-using Clockwise;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Hosting.Server.Features;
-using Microsoft.AspNetCore.ResponseCompression;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.DependencyInjection.Extensions;
-using Microsoft.Extensions.Hosting;
-using MLS.Agent.Blazor;
-using MLS.Agent.CommandLine;
-using MLS.Agent.Markdown;
-using MLS.Agent.Middleware;
-using MLS.Agent.Tools;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Serialization;
-using Pocket;
-using Recipes;
-using WorkspaceServer;
-using WorkspaceServer.Servers;
-using static Pocket.Logger;
-
-namespace MLS.Agent
-{
- public class Startup
- {
- private readonly CompositeDisposable _disposables = new CompositeDisposable
- {
- () => Logger.Log.Event("AgentStopping")
- };
-
- public Startup(
- IHostEnvironment env,
- StartupOptions startupOptions)
- {
- Environment = env;
- StartupOptions = startupOptions;
-
- var configurationBuilder = new ConfigurationBuilder()
- .SetBasePath(env.ContentRootPath);
-
- Configuration = configurationBuilder.Build();
-
- }
-
- protected IConfigurationRoot Configuration { get; }
-
- protected IHostEnvironment Environment { get; }
-
- public StartupOptions StartupOptions { get; }
-
- public void ConfigureServices(IServiceCollection services)
- {
- using (var operation = Log.OnEnterAndConfirmOnExit())
- {
- // Add framework services.
- services.AddMvc(options =>
- {
- options.EnableEndpointRouting = false;
- options.Filters.Add(new ExceptionFilter());
- options.Filters.Add(new BadRequestOnInvalidModelFilter());
-#pragma warning disable CS0618 // Type or member is obsolete
- }).SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1)
-#pragma warning restore CS0618 // Type or member is obsolete
- .AddNewtonsoftJson(o =>
- {
- o.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
- o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
- o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
- });
-
- services.AddSingleton(Configuration);
-
- services.AddSingleton(c => new WorkspaceServerMultiplexer(c.GetRequiredService()));
-
- services.TryAddSingleton