From a2e2faffce320d53b81c147c107a67c9daba1c59 Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 30 Sep 2022 13:51:47 +0200 Subject: [PATCH 01/18] Added initial support for Microsoft.NET.Sdk.Web --- src/.vscode/tasks.json | 30 +++++++-- .../NuGetMetadataReferenceResolver.cs | 4 +- .../Context/ScriptDependencyContextReader.cs | 62 +++++++++++++++++++ .../ProjectSystem/ParseResult.cs | 2 + .../ProjectSystem/ProjectFile.cs | 16 ++++- .../ProjectSystem/ScriptParser.cs | 19 +++++- .../ProjectSystem/ScriptParserInternal.cs | 12 +++- .../ProjectSystem/ScriptProjectProvider.cs | 11 ++-- .../CompilationDependencyResolverTests.cs | 10 +++ .../ScriptExecutionTests.cs | 14 ++++- .../ScriptProjectProviderTests.cs | 10 +++ .../TestFixtures/WebApi/WebApi.csx | 6 ++ 12 files changed, 175 insertions(+), 21 deletions(-) create mode 100644 src/Dotnet.Script.Tests/TestFixtures/WebApi/WebApi.csx diff --git a/src/.vscode/tasks.json b/src/.vscode/tasks.json index d123733b..b20f6f9b 100644 --- a/src/.vscode/tasks.json +++ b/src/.vscode/tasks.json @@ -6,12 +6,34 @@ "command": "dotnet", "args": [ "build", - "${workspaceRoot}/Dotnet.Script/Dotnet.Script.csproj", "/property:GenerateFullPaths=true" ], - "group": { - "kind": "build", - "isDefault": true + "options": { + "cwd": "${workspaceFolder}/.." + }, + "type": "shell", + "group": "build", + "presentation": { + "reveal": "always" + }, + "problemMatcher": "$msCompile" + }, + { + "label": "rebuild", + "command": "dotnet", + "args": [ + "build", + "--no-incremental", + "/property:GenerateFullPaths=true" + ], + "options": { + "cwd": "${workspaceFolder}/.." + }, + "type": "shell", + "group": "build", + "presentation": { + "reveal": "always", + "clear": true }, "problemMatcher": "$msCompile" }, diff --git a/src/Dotnet.Script.DependencyModel.Nuget/NuGetMetadataReferenceResolver.cs b/src/Dotnet.Script.DependencyModel.Nuget/NuGetMetadataReferenceResolver.cs index d773d9da..cd148457 100644 --- a/src/Dotnet.Script.DependencyModel.Nuget/NuGetMetadataReferenceResolver.cs +++ b/src/Dotnet.Script.DependencyModel.Nuget/NuGetMetadataReferenceResolver.cs @@ -21,7 +21,7 @@ public NuGetMetadataReferenceResolver(MetadataReferenceResolver metadataReferenc { _metadataReferenceResolver = metadataReferenceResolver; } - + public override bool Equals(object other) { return _metadataReferenceResolver.Equals(other); @@ -42,7 +42,7 @@ public override PortableExecutableReference ResolveMissingAssembly(MetadataRefer public override ImmutableArray ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { - if (reference.StartsWith("nuget", StringComparison.OrdinalIgnoreCase)) + if (reference.StartsWith("nuget", StringComparison.OrdinalIgnoreCase) || reference.StartsWith("sdk", StringComparison.OrdinalIgnoreCase)) { // HACK We need to return something here to "mark" the reference as resolved. // https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/Portable/ReferenceManager/CommonReferenceManager.Resolution.cs#L838 diff --git a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs index d12e0ee5..1d899338 100644 --- a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs +++ b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs @@ -4,8 +4,10 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; +using System.Xml.Linq; using Dotnet.Script.DependencyModel.Environment; using Dotnet.Script.DependencyModel.Logging; +using Dotnet.Script.DependencyModel.ProjectSystem; using Dotnet.Script.DependencyModel.ScriptPackage; using Microsoft.DotNet.PlatformAbstractions; using NuGet.Common; @@ -36,6 +38,10 @@ public ScriptDependencyContextReader(LogFactory logFactory) public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) { + var pathToProjectFile = GetPathToProjectFile(pathToAssetsFile); + var projectFile = XDocument.Load(pathToProjectFile); + var sdk = projectFile.Descendants("Project").Single().Attributes("Sdk").Single().Value; + var lockFile = GetLockFile(pathToAssetsFile); // Since we execute "dotnet restore -r [rid]" we get two targets in the lock file. // The second target is the one containing the runtime deps for the given RID. @@ -66,10 +72,66 @@ public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) var netcoreAppRuntimeAssemblies = Directory.GetFiles(netcoreAppRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray(); var netCoreAppDependency = new ScriptDependency("Microsoft.NETCore.App", ScriptEnvironment.Default.NetCoreVersion.Version, netcoreAppRuntimeAssemblies, Array.Empty(), Array.Empty(), Array.Empty()); scriptDependencies.Add(netCoreAppDependency); + if (sdk == "Microsoft.NET.Sdk.Web") + { + var aspNetCoreRuntimeInfo = GetAspNetCoreRuntimeInfo(netcoreAppRuntimeAssemblyLocation); + var aspNetCoreAppRuntimeAssemblies = Directory.GetFiles(aspNetCoreRuntimeInfo.aspNetCoreRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray(); + var aspNetCoreAppDependency = new ScriptDependency("Microsoft.AspNetCore.App", aspNetCoreRuntimeInfo.aspNetCoreVersion, aspNetCoreAppRuntimeAssemblies, Array.Empty(), Array.Empty(), Array.Empty()); + scriptDependencies.Add(aspNetCoreAppDependency); + } } return new ScriptDependencyContext(scriptDependencies.ToArray()); } + private static string GetPathToProjectFile(string pathToAssetsFile) + { + var pathToProjectFile = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(pathToAssetsFile), ".."), "*.csproj", SearchOption.TopDirectoryOnly).SingleOrDefault(); + if (pathToProjectFile is null) + { + pathToProjectFile = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(pathToAssetsFile), "..", "..", "..", ScriptEnvironment.Default.TargetFramework), "*.csproj", SearchOption.TopDirectoryOnly).SingleOrDefault(); + } + + if (pathToProjectFile is null) + { + throw new InvalidOperationException($"Unable to locate project file based on {pathToAssetsFile}"); + } + + return pathToProjectFile; + } + + private static (string aspNetCoreRuntimeAssemblyLocation, string aspNetCoreVersion) GetAspNetCoreRuntimeInfo(string netcoreAppRuntimeAssemblyLocation) + { + var netCoreAppRuntimeVersion = Path.GetFileName(netcoreAppRuntimeAssemblyLocation); + if (!SemanticVersion.TryParse(netCoreAppRuntimeVersion, out var version)) + { + throw new InvalidOperationException("Unable to parse version"); + } + var pathToSharedFolder = Path.GetFullPath(Path.Combine(netcoreAppRuntimeAssemblyLocation, "..", "..")); + + //Microsoft.AspNetCore.App + var pathToAspNetCoreRuntimeFolder = Directory.GetDirectories(pathToSharedFolder, "Microsoft.AspNetCore.App", SearchOption.TopDirectoryOnly).Single(); + + var aspNetCoreVersionsFolders = Directory.GetDirectories(pathToAspNetCoreRuntimeFolder).Select(folder => Path.GetFileName(folder)); + + var aspNetCoreVersions = new List(); + foreach (var aspNetCoreVersionsFolder in aspNetCoreVersionsFolders) + { + if (!SemanticVersion.TryParse(aspNetCoreVersionsFolder, out var aspNetCoreVersion)) + { + throw new InvalidOperationException("Unable to parse version"); + } + else + { + aspNetCoreVersions.Add(aspNetCoreVersion); + } + } + + var latestAspNetCoreVersion = aspNetCoreVersions.Where(v => v.Major == version.Major).OrderBy(v => v).Last(); + + return (Path.Combine(pathToAspNetCoreRuntimeFolder, latestAspNetCoreVersion.ToNormalizedString()), latestAspNetCoreVersion.ToNormalizedString()); + } + + private static bool IsAssembly(string file) { // https://docs.microsoft.com/en-us/dotnet/standard/assembly/identify diff --git a/src/Dotnet.Script.DependencyModel/ProjectSystem/ParseResult.cs b/src/Dotnet.Script.DependencyModel/ProjectSystem/ParseResult.cs index a097e422..fc2a0924 100644 --- a/src/Dotnet.Script.DependencyModel/ProjectSystem/ParseResult.cs +++ b/src/Dotnet.Script.DependencyModel/ProjectSystem/ParseResult.cs @@ -10,5 +10,7 @@ public ParseResult(IReadOnlyCollection packageReferences) } public IReadOnlyCollection PackageReferences { get; } + + public string Sdk { get; set; } } } \ No newline at end of file diff --git a/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs b/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs index 54a4e68c..52e6093b 100644 --- a/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs +++ b/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs @@ -39,6 +39,8 @@ public ProjectFile(string xmlContent) { AssemblyReferences.Add(new AssemblyReference(assemblyReference.Attribute("Include").Value)); } + + Sdk = projectFileDocument.Descendants("Project").Single().Attributes("Sdk").Single().Value; } /// @@ -61,9 +63,20 @@ public ProjectFile(string xmlContent) /// public string TargetFramework { get; set; } = ScriptEnvironment.Default.TargetFramework; + /// + /// Gets the project SDK + /// + public string Sdk { get; set; } + public void Save(string pathToProjectFile) { var projectFileDocument = XDocument.Parse(ReadTemplate("csproj.template")); + if (!string.IsNullOrEmpty(Sdk)) + { + var projectElement = projectFileDocument.Descendants("Project").Single(); + projectElement.Attributes("Sdk").Single().Value = Sdk; + } + var itemGroupElement = projectFileDocument.Descendants("ItemGroup").Single(); foreach (var packageReference in PackageReferences) { @@ -101,7 +114,8 @@ public bool Equals(ProjectFile other) if (ReferenceEquals(this, other)) return true; return PackageReferences.SequenceEqual(other.PackageReferences) && AssemblyReferences.SequenceEqual(other.AssemblyReferences) - && TargetFramework.Equals(other.TargetFramework); + && TargetFramework.Equals(other.TargetFramework) + && Sdk.Equals(other.Sdk); } /// diff --git a/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParser.cs b/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParser.cs index b6a8e4b5..91b6b2a4 100644 --- a/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParser.cs +++ b/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParser.cs @@ -26,26 +26,39 @@ public ParseResult ParseFromCode(string code) public ParseResult ParseFromFiles(IEnumerable csxFiles) { var allPackageReferences = new HashSet(); + string sdk = string.Empty; foreach (var csxFile in csxFiles) { _logger.Debug($"Parsing {csxFile}"); var fileContent = File.ReadAllText(csxFile); allPackageReferences.UnionWith(ReadPackageReferencesFromReferenceDirective(fileContent)); allPackageReferences.UnionWith(ReadPackageReferencesFromLoadDirective(fileContent)); + var sdkReference = ReadSdkFromReferenceDirective(fileContent); + if (!string.IsNullOrWhiteSpace(sdkReference)) + { + sdk = sdkReference; + } } - return new ParseResult(allPackageReferences); + return new ParseResult(allPackageReferences) { Sdk = sdk }; + } + + private static string ReadSdkFromReferenceDirective(string fileContent) + { + const string pattern = DirectivePatternPrefix + "r" + SdkDirectivePatternSuffix; + var match = Regex.Match(fileContent, pattern); + return match.Success ? match.Groups[1].Value : string.Empty; } private static IEnumerable ReadPackageReferencesFromReferenceDirective(string fileContent) { - const string pattern = DirectivePatternPrefix + "r" + DirectivePatternSuffix; + const string pattern = DirectivePatternPrefix + "r" + NuGetDirectivePatternSuffix; return ReadPackageReferencesFromDirective(pattern, fileContent); } private static IEnumerable ReadPackageReferencesFromLoadDirective(string fileContent) { - const string pattern = DirectivePatternPrefix + "load" + DirectivePatternSuffix; + const string pattern = DirectivePatternPrefix + "load" + NuGetDirectivePatternSuffix; return ReadPackageReferencesFromDirective(pattern, fileContent); } diff --git a/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParserInternal.cs b/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParserInternal.cs index c931b700..72c3fb5c 100644 --- a/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParserInternal.cs +++ b/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParserInternal.cs @@ -7,14 +7,20 @@ partial class ScriptParser const string Hws = @"[\x20\t]*"; // hws = horizontal whitespace const string NuGetPattern = @"nuget:" - // https://github.com/NuGet/docs.microsoft.com-nuget/issues/543#issue-270039223 + // https://github.com/NuGet/docs.microsoft.com-nuget/issues/543#issue-270039223 + Hws + @"(\w+(?:[_.-]\w+)*)" + @"(?:" + Hws + "," + Hws + @"(.+?))?"; + const string SdkPattern = @"sdk:" + + Hws + @"(\w+(?:[_.-]\w+)*)" + + @"(?:" + Hws + @")?"; + const string WholeNuGetPattern = @"^" + NuGetPattern + @"$"; const string DirectivePatternPrefix = @"^" + Hws + @"#"; - const string DirectivePatternSuffix = Hws + @"""" + NuGetPattern + @""""; + const string NuGetDirectivePatternSuffix = Hws + @"""" + NuGetPattern + @""""; + + const string SdkDirectivePatternSuffix = Hws + @"""" + SdkPattern + @""""; internal static bool TryParseNuGetPackageReference(string input, out string id, out string version) @@ -22,7 +28,7 @@ internal static bool TryParseNuGetPackageReference(string input, bool success; (success, id, version) = Regex.Match(input, WholeNuGetPattern, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase) - is {} match && match.Success + is { } match && match.Success ? (true, match.Groups[1].Value, match.Groups[2].Value) : default; return success; diff --git a/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptProjectProvider.cs b/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptProjectProvider.cs index 377bf5e2..a050c64f 100644 --- a/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptProjectProvider.cs +++ b/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptProjectProvider.cs @@ -1,11 +1,8 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text.RegularExpressions; using Dotnet.Script.DependencyModel.Environment; using Dotnet.Script.DependencyModel.Logging; -using Dotnet.Script.DependencyModel.Process; namespace Dotnet.Script.DependencyModel.ProjectSystem { @@ -57,6 +54,7 @@ public ProjectFileInfo CreateProjectForRepl(string code, string targetDirectory, } projectFile.TargetFramework = defaultTargetFramework; + projectFile.Sdk = parseResultFromCode.Sdk; projectFile.Save(pathToProjectFile); @@ -116,16 +114,17 @@ private ProjectFileInfo SaveProjectFileFromScriptFiles(string targetDirectory, s public ProjectFile CreateProjectFileFromScriptFiles(string defaultTargetFramework, string[] csxFiles) { - var parseresult = _scriptParser.ParseFromFiles(csxFiles); + var parseResult = _scriptParser.ParseFromFiles(csxFiles); var projectFile = new ProjectFile(); - foreach (var packageReference in parseresult.PackageReferences) + foreach (var packageReference in parseResult.PackageReferences) { projectFile.PackageReferences.Add(packageReference); } projectFile.TargetFramework = defaultTargetFramework; + projectFile.Sdk = parseResult.Sdk; return projectFile; } diff --git a/src/Dotnet.Script.Tests/CompilationDependencyResolverTests.cs b/src/Dotnet.Script.Tests/CompilationDependencyResolverTests.cs index 5e3652d9..17be547a 100644 --- a/src/Dotnet.Script.Tests/CompilationDependencyResolverTests.cs +++ b/src/Dotnet.Script.Tests/CompilationDependencyResolverTests.cs @@ -72,6 +72,16 @@ public void ShouldGetCompilationDependenciesForIssue129() Assert.Contains(dependencies, d => d.Name == "Auth0.ManagementApi"); } + [Fact] + public void ShouldGetCompilationDependenciesForWebSdk() + { + var resolver = CreateResolver(); + var targetDirectory = TestPathUtils.GetPathToTestFixtureFolder("WebApi"); + var csxFiles = Directory.GetFiles(targetDirectory, "*.csx"); + var dependencies = resolver.GetDependencies(targetDirectory, csxFiles, true, _scriptEnvironment.TargetFramework); + Assert.Contains(dependencies.SelectMany(d => d.AssemblyPaths), p => p.Contains("Microsoft.AspNetCore.Components")); + } + private CompilationDependencyResolver CreateResolver() { var resolver = new CompilationDependencyResolver(TestOutputHelper.CreateTestLogFactory()); diff --git a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs index 0d56d592..a332247c 100644 --- a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs +++ b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs @@ -21,8 +21,9 @@ public ScriptExecutionTests(ITestOutputHelper testOutputHelper) [Fact] public void ShouldExecuteHelloWorld() { - var (output, _) = ScriptTestRunner.Default.ExecuteFixture("HelloWorld", "--no-cache"); - Assert.Contains("Hello World", output); + ScriptTestRunner.ExecuteFixtureInProcess("HelloWorld", "--no-cache"); + // var (output, _) = ScriptTestRunner.Default.ExecuteFixture("HelloWorld", "--no-cache"); + // Assert.Contains("Hello World", output); } [Fact] @@ -479,6 +480,15 @@ public void ShouldSetCurrentContextualReflectionContext() Assert.Contains("Dotnet.Script.Core.ScriptAssemblyLoadContext", output); } + [Fact] + public void ShouldCompileAndExecuteWithWebSdk() + { + var test = ScriptTestRunner.ExecuteFixtureInProcess("WebApi", "--no-cache --isolated-load-context"); + + // var (output, _) = ScriptTestRunner.Default.ExecuteFixture("CurrentContextualReflectionContext", "--isolated-load-context"); + // Assert.Contains("Dotnet.Script.Core.ScriptAssemblyLoadContext", output); + } + private static string CreateTestScript(string scriptFolder) { string script = @" diff --git a/src/Dotnet.Script.Tests/ScriptProjectProviderTests.cs b/src/Dotnet.Script.Tests/ScriptProjectProviderTests.cs index 46f530e7..9d87775f 100644 --- a/src/Dotnet.Script.Tests/ScriptProjectProviderTests.cs +++ b/src/Dotnet.Script.Tests/ScriptProjectProviderTests.cs @@ -1,5 +1,7 @@ using System.IO; +using System.Linq; using System.Text; +using System.Xml.Linq; using Dotnet.Script.DependencyModel.Environment; using Dotnet.Script.DependencyModel.ProjectSystem; using Dotnet.Script.Shared.Tests; @@ -30,5 +32,13 @@ public void ShouldLogProjectFileContent() Assert.Contains("", output); } + + [Fact] + public void ShouldUseSpecifiedSdk() + { + var provider = new ScriptProjectProvider(TestOutputHelper.CreateTestLogFactory()); + var projectFileInfo = provider.CreateProject(TestPathUtils.GetPathToTestFixtureFolder("WebApi"), _scriptEnvironment.TargetFramework, true); + Assert.Equal("Microsoft.NET.Sdk.Web", XDocument.Load(projectFileInfo.Path).Descendants("Project").Single().Attributes("Sdk").Single().Value); + } } } \ No newline at end of file diff --git a/src/Dotnet.Script.Tests/TestFixtures/WebApi/WebApi.csx b/src/Dotnet.Script.Tests/TestFixtures/WebApi/WebApi.csx new file mode 100644 index 00000000..b4b76d41 --- /dev/null +++ b/src/Dotnet.Script.Tests/TestFixtures/WebApi/WebApi.csx @@ -0,0 +1,6 @@ +#r "sdk:Microsoft.NET.Sdk.Web" + +using Microsoft.AspNetCore.Builder; + +var a = WebApplication.Create(); +a.MapGet("/", () => "Hello world"); \ No newline at end of file From bd4efc9982038b8f7a1c4797b54da2cff88552c9 Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 30 Sep 2022 15:56:16 +0200 Subject: [PATCH 02/18] Inspect project.assets.json for Microsoft.AspNetCore.App --- .../Context/ScriptDependencyContextReader.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs index 1d899338..c7a0e944 100644 --- a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs +++ b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs @@ -38,14 +38,16 @@ public ScriptDependencyContextReader(LogFactory logFactory) public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) { - var pathToProjectFile = GetPathToProjectFile(pathToAssetsFile); - var projectFile = XDocument.Load(pathToProjectFile); - var sdk = projectFile.Descendants("Project").Single().Attributes("Sdk").Single().Value; + // var pathToProjectFile = GetPathToProjectFile(pathToAssetsFile); + // var projectFile = XDocument.Load(pathToProjectFile); + // var sdk = projectFile.Descendants("Project").Single().Attributes("Sdk").Single().Value; var lockFile = GetLockFile(pathToAssetsFile); + // Since we execute "dotnet restore -r [rid]" we get two targets in the lock file. // The second target is the one containing the runtime deps for the given RID. var target = GetLockFileTarget(lockFile); + var targetLibraries = target.Libraries; var packageFolders = lockFile.PackageFolders.Select(lfi => lfi.Path).ToArray(); var userPackageFolder = packageFolders.First(); @@ -72,7 +74,7 @@ public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) var netcoreAppRuntimeAssemblies = Directory.GetFiles(netcoreAppRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray(); var netCoreAppDependency = new ScriptDependency("Microsoft.NETCore.App", ScriptEnvironment.Default.NetCoreVersion.Version, netcoreAppRuntimeAssemblies, Array.Empty(), Array.Empty(), Array.Empty()); scriptDependencies.Add(netCoreAppDependency); - if (sdk == "Microsoft.NET.Sdk.Web") + if (File.ReadAllText(pathToAssetsFile).Contains("Microsoft.AspNetCore.App")) { var aspNetCoreRuntimeInfo = GetAspNetCoreRuntimeInfo(netcoreAppRuntimeAssemblyLocation); var aspNetCoreAppRuntimeAssemblies = Directory.GetFiles(aspNetCoreRuntimeInfo.aspNetCoreRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray(); From 3b45c1e45be2a9b910f6caf4c073737aa98b20ab Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 30 Sep 2022 17:12:25 +0200 Subject: [PATCH 03/18] Set default Sdk --- src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs b/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs index 52e6093b..35738a71 100644 --- a/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs +++ b/src/Dotnet.Script.DependencyModel/ProjectSystem/ProjectFile.cs @@ -66,7 +66,7 @@ public ProjectFile(string xmlContent) /// /// Gets the project SDK /// - public string Sdk { get; set; } + public string Sdk { get; set; } = "Microsoft.NET.Sdk"; public void Save(string pathToProjectFile) { From 09efd8013b636579bd074e0a7a21477d5bd1a17b Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 30 Sep 2022 20:48:53 +0200 Subject: [PATCH 04/18] Match whole word for Microsoft.AspNetCore.App --- .../Context/ScriptDependencyContextReader.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs index c7a0e944..409ea708 100644 --- a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs +++ b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs @@ -74,7 +74,7 @@ public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) var netcoreAppRuntimeAssemblies = Directory.GetFiles(netcoreAppRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray(); var netCoreAppDependency = new ScriptDependency("Microsoft.NETCore.App", ScriptEnvironment.Default.NetCoreVersion.Version, netcoreAppRuntimeAssemblies, Array.Empty(), Array.Empty(), Array.Empty()); scriptDependencies.Add(netCoreAppDependency); - if (File.ReadAllText(pathToAssetsFile).Contains("Microsoft.AspNetCore.App")) + if (File.ReadAllText(pathToAssetsFile).Contains("\"Microsoft.AspNetCore.App\"")) { var aspNetCoreRuntimeInfo = GetAspNetCoreRuntimeInfo(netcoreAppRuntimeAssemblyLocation); var aspNetCoreAppRuntimeAssemblies = Directory.GetFiles(aspNetCoreRuntimeInfo.aspNetCoreRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray(); From 5d0929651fdd6e89ecee87052dd89e4a0477d9da Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Tue, 22 Nov 2022 23:12:05 +0100 Subject: [PATCH 05/18] Improved ScriptDependencyContextReader --- src/Dotnet.Script.Core/Dotnet.Script.Core.csproj | 9 +++++---- .../Context/ScriptDependencyContextReader.cs | 16 +++++++++++----- src/Dotnet.Script.Tests/ScriptExecutionTests.cs | 5 +++-- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/Dotnet.Script.Core/Dotnet.Script.Core.csproj b/src/Dotnet.Script.Core/Dotnet.Script.Core.csproj index ff2f9d10..fd21ef42 100644 --- a/src/Dotnet.Script.Core/Dotnet.Script.Core.csproj +++ b/src/Dotnet.Script.Core/Dotnet.Script.Core.csproj @@ -28,13 +28,14 @@ - + - - - + + + + diff --git a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs index 409ea708..39a82e93 100644 --- a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs +++ b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs @@ -15,6 +15,8 @@ using NuGet.ProjectModel; using NuGet.RuntimeModel; using NuGet.Versioning; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; namespace Dotnet.Script.DependencyModel.Context { @@ -38,10 +40,6 @@ public ScriptDependencyContextReader(LogFactory logFactory) public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) { - // var pathToProjectFile = GetPathToProjectFile(pathToAssetsFile); - // var projectFile = XDocument.Load(pathToProjectFile); - // var sdk = projectFile.Descendants("Project").Single().Attributes("Sdk").Single().Value; - var lockFile = GetLockFile(pathToAssetsFile); // Since we execute "dotnet restore -r [rid]" we get two targets in the lock file. @@ -74,7 +72,8 @@ public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) var netcoreAppRuntimeAssemblies = Directory.GetFiles(netcoreAppRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray(); var netCoreAppDependency = new ScriptDependency("Microsoft.NETCore.App", ScriptEnvironment.Default.NetCoreVersion.Version, netcoreAppRuntimeAssemblies, Array.Empty(), Array.Empty(), Array.Empty()); scriptDependencies.Add(netCoreAppDependency); - if (File.ReadAllText(pathToAssetsFile).Contains("\"Microsoft.AspNetCore.App\"")) + //if (File.ReadAllText(pathToAssetsFile).Contains("\"Microsoft.AspNetCore.App\"")) + if (HasAspNetCoreFrameworkReference(pathToAssetsFile)) { var aspNetCoreRuntimeInfo = GetAspNetCoreRuntimeInfo(netcoreAppRuntimeAssemblyLocation); var aspNetCoreAppRuntimeAssemblies = Directory.GetFiles(aspNetCoreRuntimeInfo.aspNetCoreRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray(); @@ -85,6 +84,13 @@ public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) return new ScriptDependencyContext(scriptDependencies.ToArray()); } + private bool HasAspNetCoreFrameworkReference(string pathToAssetsFile) + { + JObject assetsFile = JObject.Parse(File.ReadAllText(pathToAssetsFile)); + return assetsFile["project"]?["frameworks"]?["net7.0"]?["frameworkReferences"]?["Microsoft.AspNetCore.App"] != null; + } + + private static string GetPathToProjectFile(string pathToAssetsFile) { var pathToProjectFile = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(pathToAssetsFile), ".."), "*.csproj", SearchOption.TopDirectoryOnly).SingleOrDefault(); diff --git a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs index 38c28d1b..687930ae 100644 --- a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs +++ b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs @@ -483,8 +483,9 @@ public void ShouldSetCurrentContextualReflectionContext() [Fact] public void ShouldCompileAndExecuteWithWebSdk() { - var test = ScriptTestRunner.ExecuteFixtureInProcess("WebApi", "--no-cache --isolated-load-context"); - + // var test = ScriptTestRunner.ExecuteFixtureInProcess("WebApi", "--no-cache --isolated-load-context"); + var test = ScriptTestRunner.ExecuteFixtureInProcess("WebApi", "--no-cache --debug"); + Assert.Equal(0, test); // var (output, _) = ScriptTestRunner.Default.ExecuteFixture("CurrentContextualReflectionContext", "--isolated-load-context"); // Assert.Contains("Dotnet.Script.Core.ScriptAssemblyLoadContext", output); } From 03004ba7d781159e4a126311c94a8fdf44dcbd73 Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Thu, 24 Nov 2022 22:01:12 +0100 Subject: [PATCH 06/18] Use target framework from ScriptEnvironment --- global.json | 2 +- .../Context/ScriptDependencyContextReader.cs | 3 +-- src/Dotnet.Script.Tests/ScriptExecutionTests.cs | 8 +++++--- src/Dotnet.Script/Dotnet.Script.csproj | 4 +++- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/global.json b/global.json index b68e0c11..d4d08251 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "7.0.100-rc.1.22431.12", + "version": "7.0.100", "rollForward": "latestFeature" } } diff --git a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs index 39a82e93..70761a5a 100644 --- a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs +++ b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs @@ -87,10 +87,9 @@ public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) private bool HasAspNetCoreFrameworkReference(string pathToAssetsFile) { JObject assetsFile = JObject.Parse(File.ReadAllText(pathToAssetsFile)); - return assetsFile["project"]?["frameworks"]?["net7.0"]?["frameworkReferences"]?["Microsoft.AspNetCore.App"] != null; + return assetsFile["project"]?["frameworks"]?[ScriptEnvironment.Default.TargetFramework]?["frameworkReferences"]?["Microsoft.AspNetCore.App"] != null; } - private static string GetPathToProjectFile(string pathToAssetsFile) { var pathToProjectFile = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(pathToAssetsFile), ".."), "*.csproj", SearchOption.TopDirectoryOnly).SingleOrDefault(); diff --git a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs index 687930ae..4c77bac8 100644 --- a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs +++ b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs @@ -483,9 +483,11 @@ public void ShouldSetCurrentContextualReflectionContext() [Fact] public void ShouldCompileAndExecuteWithWebSdk() { - // var test = ScriptTestRunner.ExecuteFixtureInProcess("WebApi", "--no-cache --isolated-load-context"); - var test = ScriptTestRunner.ExecuteFixtureInProcess("WebApi", "--no-cache --debug"); - Assert.Equal(0, test); + var processResult = ScriptTestRunner.Default.ExecuteFixture("WebApi", "--no-cache"); + Assert.Equal(0, processResult.ExitCode); + + // var test = ScriptTestRunner.ExecuteFixtureInProcess("WebApi", "--no-cache --debug"); + // Assert.Equal(0, test); // var (output, _) = ScriptTestRunner.Default.ExecuteFixture("CurrentContextualReflectionContext", "--isolated-load-context"); // Assert.Contains("Dotnet.Script.Core.ScriptAssemblyLoadContext", output); } diff --git a/src/Dotnet.Script/Dotnet.Script.csproj b/src/Dotnet.Script/Dotnet.Script.csproj index 5c4497e1..a0e444b8 100644 --- a/src/Dotnet.Script/Dotnet.Script.csproj +++ b/src/Dotnet.Script/Dotnet.Script.csproj @@ -26,7 +26,9 @@ - + + + From 5fffe9f02e774c7bb0a1b1c37c31659ca8a79f35 Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Thu, 24 Nov 2022 22:42:52 +0100 Subject: [PATCH 07/18] Onlu support Microsoft.NET.Sdk.Web --- .../ProjectSystem/ScriptParser.cs | 19 +++++++++++++++++-- .../ScriptExecutionTests.cs | 7 +++++++ .../UnsupportedSdk/UnsupportedSdk.csx | 1 + 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 src/Dotnet.Script.Tests/TestFixtures/UnsupportedSdk/UnsupportedSdk.csx diff --git a/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParser.cs b/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParser.cs index 91b6b2a4..0d058a21 100644 --- a/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParser.cs +++ b/src/Dotnet.Script.DependencyModel/ProjectSystem/ScriptParser.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; @@ -20,7 +21,13 @@ public ParseResult ParseFromCode(string code) var allPackageReferences = new HashSet(); allPackageReferences.UnionWith(ReadPackageReferencesFromReferenceDirective(code)); allPackageReferences.UnionWith(ReadPackageReferencesFromLoadDirective(code)); - return new ParseResult(allPackageReferences); + var sdkReference = ReadSdkFromReferenceDirective(code); + string sdk = string.Empty; + if (!string.IsNullOrWhiteSpace(sdkReference)) + { + sdk = sdkReference; + } + return new ParseResult(allPackageReferences) { Sdk = sdk }; } public ParseResult ParseFromFiles(IEnumerable csxFiles) @@ -47,6 +54,14 @@ private static string ReadSdkFromReferenceDirective(string fileContent) { const string pattern = DirectivePatternPrefix + "r" + SdkDirectivePatternSuffix; var match = Regex.Match(fileContent, pattern); + if (match.Success) + { + var sdk = match.Groups[1].Value; + if (!string.Equals(sdk, "Microsoft.NET.Sdk.Web", System.StringComparison.InvariantCultureIgnoreCase)) + { + throw new NotSupportedException($"The sdk '{sdk}' is not supported. Currently 'Microsoft.NET.Sdk.Web' is the only sdk supported."); + } + } return match.Success ? match.Groups[1].Value : string.Empty; } diff --git a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs index 4c77bac8..f8fd4293 100644 --- a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs +++ b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs @@ -492,6 +492,13 @@ public void ShouldCompileAndExecuteWithWebSdk() // Assert.Contains("Dotnet.Script.Core.ScriptAssemblyLoadContext", output); } + [Fact] + public void ShouldThrowExceptionWhenSdkIsNotSupported() + { + var processResult = ScriptTestRunner.Default.ExecuteFixture("UnsupportedSdk", "--no-cache"); + Assert.StartsWith("The sdk 'Unsupported' is not supported", processResult.StandardError); + } + private static string CreateTestScript(string scriptFolder) { string script = @" diff --git a/src/Dotnet.Script.Tests/TestFixtures/UnsupportedSdk/UnsupportedSdk.csx b/src/Dotnet.Script.Tests/TestFixtures/UnsupportedSdk/UnsupportedSdk.csx new file mode 100644 index 00000000..4f30c5e3 --- /dev/null +++ b/src/Dotnet.Script.Tests/TestFixtures/UnsupportedSdk/UnsupportedSdk.csx @@ -0,0 +1 @@ +#r "sdk:Unsupported" \ No newline at end of file From a7b59b06b4b889295d2abac068019c5931bde980 Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Thu, 24 Nov 2022 22:55:16 +0100 Subject: [PATCH 08/18] Bump McMaster.Extensions.CommandLineUtils --- src/Dotnet.Script/Dotnet.Script.csproj | 88 +++++++++++++------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/src/Dotnet.Script/Dotnet.Script.csproj b/src/Dotnet.Script/Dotnet.Script.csproj index 3a8302e8..3d3c723c 100644 --- a/src/Dotnet.Script/Dotnet.Script.csproj +++ b/src/Dotnet.Script/Dotnet.Script.csproj @@ -1,44 +1,44 @@ - - - Dotnet CLI tool allowing you to run C# (CSX) scripts. - 1.4.0 - filipw - Dotnet.Script - net7.0;net6.0 - portable - dotnet-script - Exe - dotnet;cli;script;csx;csharp;roslyn - https://avatars.githubusercontent.com/u/113979420 - https://github.com/dotnet-script/dotnet-script - MIT - git - https://github.com/dotnet-script/dotnet-script.git - false - false - false - false - true - latest - true - ../dotnet-script.snk - - - - - - - - - - - - - - Always - - - Always - - - + + + + Dotnet CLI tool allowing you to run C# (CSX) scripts. + 1.4.0 + filipw + Dotnet.Script + net7.0;net6.0 + portable + dotnet-script + Exe + dotnet;cli;script;csx;csharp;roslyn + https://avatars.githubusercontent.com/u/113979420 + https://github.com/dotnet-script/dotnet-script + MIT + git + https://github.com/dotnet-script/dotnet-script.git + false + false + false + false + true + latest + true + ../dotnet-script.snk + + + + + + + + + + + + + Always + + + Always + + + \ No newline at end of file From 87050139c4c6feff354c9b3ee9c2dc59b48fbb22 Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Thu, 24 Nov 2022 23:25:03 +0100 Subject: [PATCH 09/18] Removed no longer needed dependencies and bumped existing --- src/.vscode/tasks.json | 2 +- src/Dotnet.Script.Core/Dotnet.Script.Core.csproj | 15 ++++----------- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/src/.vscode/tasks.json b/src/.vscode/tasks.json index b20f6f9b..e35e8bda 100644 --- a/src/.vscode/tasks.json +++ b/src/.vscode/tasks.json @@ -46,7 +46,7 @@ "-c", "release", "-f", - "net6.0", + "net7.0", "${workspaceFolder}/Dotnet.Script.Tests/DotNet.Script.Tests.csproj" ], "problemMatcher": "$msCompile", diff --git a/src/Dotnet.Script.Core/Dotnet.Script.Core.csproj b/src/Dotnet.Script.Core/Dotnet.Script.Core.csproj index 420af2d6..094312d6 100644 --- a/src/Dotnet.Script.Core/Dotnet.Script.Core.csproj +++ b/src/Dotnet.Script.Core/Dotnet.Script.Core.csproj @@ -24,22 +24,15 @@ - - + + - - - - - - - - - + + From 6aa85f4c9fc23ff16613690d7c70a1a1d34e13bb Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 25 Nov 2022 00:13:05 +0100 Subject: [PATCH 10/18] Added REPL test for Microsoft.NET.Sdk.Web --- .../InteractiveRunnerTestsBase.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/Dotnet.Script.Shared.Tests/InteractiveRunnerTestsBase.cs b/src/Dotnet.Script.Shared.Tests/InteractiveRunnerTestsBase.cs index f6a90d74..7b04e85c 100644 --- a/src/Dotnet.Script.Shared.Tests/InteractiveRunnerTestsBase.cs +++ b/src/Dotnet.Script.Shared.Tests/InteractiveRunnerTestsBase.cs @@ -307,5 +307,25 @@ public async Task ScriptPackageReferenceAsTheFirstLine() var result = ctx.Console.Out.ToString(); Assert.Contains("[Submission#0+SimpleTargets+TargetDictionary]", result); } + + [Fact] + public async Task ShouldCompileAndExecuteWithWebSdk() + { + var commands = new[] + { + @"#r ""sdk:Microsoft.NET.Sdk.Web""", + "using Microsoft.AspNetCore.Builder;", + "var a = WebApplication.Create();", + @"a.GetType()", + "#exit" + }; + + var ctx = GetRunner(commands); + await ctx.Runner.RunLoop(); + + var result = ctx.Console.Out.ToString(); + + Assert.Contains("[Microsoft.AspNetCore.Builder.WebApplication]", result); + } } } From 3f8d0bf069283af30f6a47adac3c8a9b3ebb3bf1 Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 25 Nov 2022 13:08:20 +0100 Subject: [PATCH 11/18] Only run Web Sdk Interactive tests on net6.0 and net7.0 --- .../InteractiveRunnerTestsBase.cs | 24 ++----------------- .../InteractiveRunnerTests.cs | 21 ++++++++++++++++ 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/src/Dotnet.Script.Shared.Tests/InteractiveRunnerTestsBase.cs b/src/Dotnet.Script.Shared.Tests/InteractiveRunnerTestsBase.cs index 7b04e85c..14996185 100644 --- a/src/Dotnet.Script.Shared.Tests/InteractiveRunnerTestsBase.cs +++ b/src/Dotnet.Script.Shared.Tests/InteractiveRunnerTestsBase.cs @@ -17,7 +17,7 @@ public InteractiveRunnerTestsBase(ITestOutputHelper testOutputHelper) testOutputHelper.Capture(); } - private class InteractiveTestContext + protected class InteractiveTestContext { public InteractiveTestContext(ScriptConsole console, InteractiveRunner runner) { @@ -29,7 +29,7 @@ public InteractiveTestContext(ScriptConsole console, InteractiveRunner runner) public InteractiveRunner Runner { get; } } - private InteractiveTestContext GetRunner(params string[] commands) + protected InteractiveTestContext GetRunner(params string[] commands) { var reader = new StringReader(string.Join(Environment.NewLine, commands)); var writer = new StringWriter(); @@ -307,25 +307,5 @@ public async Task ScriptPackageReferenceAsTheFirstLine() var result = ctx.Console.Out.ToString(); Assert.Contains("[Submission#0+SimpleTargets+TargetDictionary]", result); } - - [Fact] - public async Task ShouldCompileAndExecuteWithWebSdk() - { - var commands = new[] - { - @"#r ""sdk:Microsoft.NET.Sdk.Web""", - "using Microsoft.AspNetCore.Builder;", - "var a = WebApplication.Create();", - @"a.GetType()", - "#exit" - }; - - var ctx = GetRunner(commands); - await ctx.Runner.RunLoop(); - - var result = ctx.Console.Out.ToString(); - - Assert.Contains("[Microsoft.AspNetCore.Builder.WebApplication]", result); - } } } diff --git a/src/Dotnet.Script.Tests/InteractiveRunnerTests.cs b/src/Dotnet.Script.Tests/InteractiveRunnerTests.cs index aa1a5ff4..666b0035 100644 --- a/src/Dotnet.Script.Tests/InteractiveRunnerTests.cs +++ b/src/Dotnet.Script.Tests/InteractiveRunnerTests.cs @@ -1,6 +1,7 @@ using Xunit; using Dotnet.Script.Shared.Tests; using Xunit.Abstractions; +using System.Threading.Tasks; namespace Dotnet.Script.Tests { @@ -10,5 +11,25 @@ public class InteractiveRunnerTests : InteractiveRunnerTestsBase public InteractiveRunnerTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { } + + [Fact] + public async Task ShouldCompileAndExecuteWithWebSdk() + { + var commands = new[] + { + @"#r ""sdk:Microsoft.NET.Sdk.Web""", + "using Microsoft.AspNetCore.Builderss;", + "var a = WebApplication.Create();", + @"a.GetType()", + "#exit" + }; + + var ctx = GetRunner(commands); + await ctx.Runner.RunLoop(); + + var result = ctx.Console.Out.ToString(); + + Assert.Contains("[Microsoft.AspNetCore.Builder.WebApplication]", result); + } } } From 788ff3a07c85e67b761d415e7786a6b914479e13 Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 25 Nov 2022 13:20:19 +0100 Subject: [PATCH 12/18] Fixed type in test --- src/Dotnet.Script.Tests/InteractiveRunnerTests.cs | 4 ++-- src/Dotnet.Script/Dotnet.Script.csproj | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Dotnet.Script.Tests/InteractiveRunnerTests.cs b/src/Dotnet.Script.Tests/InteractiveRunnerTests.cs index 666b0035..eba5ff06 100644 --- a/src/Dotnet.Script.Tests/InteractiveRunnerTests.cs +++ b/src/Dotnet.Script.Tests/InteractiveRunnerTests.cs @@ -18,7 +18,7 @@ public async Task ShouldCompileAndExecuteWithWebSdk() var commands = new[] { @"#r ""sdk:Microsoft.NET.Sdk.Web""", - "using Microsoft.AspNetCore.Builderss;", + "using Microsoft.AspNetCore.Builder;", "var a = WebApplication.Create();", @"a.GetType()", "#exit" @@ -28,7 +28,7 @@ public async Task ShouldCompileAndExecuteWithWebSdk() await ctx.Runner.RunLoop(); var result = ctx.Console.Out.ToString(); - + var error = ctx.Console.Error.ToString(); Assert.Contains("[Microsoft.AspNetCore.Builder.WebApplication]", result); } } diff --git a/src/Dotnet.Script/Dotnet.Script.csproj b/src/Dotnet.Script/Dotnet.Script.csproj index 3d3c723c..10f10c13 100644 --- a/src/Dotnet.Script/Dotnet.Script.csproj +++ b/src/Dotnet.Script/Dotnet.Script.csproj @@ -28,7 +28,6 @@ - From b61d16e4b21317c7f71970511753c6323614a13f Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 25 Nov 2022 13:29:27 +0100 Subject: [PATCH 13/18] Cleanup in ScriptDependencyContextReader --- .../Context/ScriptDependencyContextReader.cs | 33 ++++--------------- .../ScriptExecutionTests.cs | 5 --- 2 files changed, 7 insertions(+), 31 deletions(-) diff --git a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs index 70761a5a..cd78b179 100644 --- a/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs +++ b/src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs @@ -4,18 +4,13 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; -using System.Xml.Linq; using Dotnet.Script.DependencyModel.Environment; using Dotnet.Script.DependencyModel.Logging; -using Dotnet.Script.DependencyModel.ProjectSystem; using Dotnet.Script.DependencyModel.ScriptPackage; -using Microsoft.DotNet.PlatformAbstractions; using NuGet.Common; using NuGet.Packaging; using NuGet.ProjectModel; -using NuGet.RuntimeModel; using NuGet.Versioning; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Dotnet.Script.DependencyModel.Context @@ -72,7 +67,6 @@ public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile) var netcoreAppRuntimeAssemblies = Directory.GetFiles(netcoreAppRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray(); var netCoreAppDependency = new ScriptDependency("Microsoft.NETCore.App", ScriptEnvironment.Default.NetCoreVersion.Version, netcoreAppRuntimeAssemblies, Array.Empty(), Array.Empty(), Array.Empty()); scriptDependencies.Add(netCoreAppDependency); - //if (File.ReadAllText(pathToAssetsFile).Contains("\"Microsoft.AspNetCore.App\"")) if (HasAspNetCoreFrameworkReference(pathToAssetsFile)) { var aspNetCoreRuntimeInfo = GetAspNetCoreRuntimeInfo(netcoreAppRuntimeAssemblyLocation); @@ -90,33 +84,20 @@ private bool HasAspNetCoreFrameworkReference(string pathToAssetsFile) return assetsFile["project"]?["frameworks"]?[ScriptEnvironment.Default.TargetFramework]?["frameworkReferences"]?["Microsoft.AspNetCore.App"] != null; } - private static string GetPathToProjectFile(string pathToAssetsFile) - { - var pathToProjectFile = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(pathToAssetsFile), ".."), "*.csproj", SearchOption.TopDirectoryOnly).SingleOrDefault(); - if (pathToProjectFile is null) - { - pathToProjectFile = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(pathToAssetsFile), "..", "..", "..", ScriptEnvironment.Default.TargetFramework), "*.csproj", SearchOption.TopDirectoryOnly).SingleOrDefault(); - } - - if (pathToProjectFile is null) - { - throw new InvalidOperationException($"Unable to locate project file based on {pathToAssetsFile}"); - } - - return pathToProjectFile; - } - private static (string aspNetCoreRuntimeAssemblyLocation, string aspNetCoreVersion) GetAspNetCoreRuntimeInfo(string netcoreAppRuntimeAssemblyLocation) { var netCoreAppRuntimeVersion = Path.GetFileName(netcoreAppRuntimeAssemblyLocation); if (!SemanticVersion.TryParse(netCoreAppRuntimeVersion, out var version)) { - throw new InvalidOperationException("Unable to parse version"); + throw new InvalidOperationException($"Unable to parse netcore app version '{netCoreAppRuntimeVersion}'"); } var pathToSharedFolder = Path.GetFullPath(Path.Combine(netcoreAppRuntimeAssemblyLocation, "..", "..")); - //Microsoft.AspNetCore.App - var pathToAspNetCoreRuntimeFolder = Directory.GetDirectories(pathToSharedFolder, "Microsoft.AspNetCore.App", SearchOption.TopDirectoryOnly).Single(); + var pathToAspNetCoreRuntimeFolder = Directory.GetDirectories(pathToSharedFolder, "Microsoft.AspNetCore.App", SearchOption.TopDirectoryOnly).SingleOrDefault(); + if (string.IsNullOrWhiteSpace(pathToAspNetCoreRuntimeFolder)) + { + throw new InvalidOperationException($"Failed to resolve the path to 'Microsoft.AspNetCore.App' in {pathToSharedFolder}"); + } var aspNetCoreVersionsFolders = Directory.GetDirectories(pathToAspNetCoreRuntimeFolder).Select(folder => Path.GetFileName(folder)); @@ -125,7 +106,7 @@ private static (string aspNetCoreRuntimeAssemblyLocation, string aspNetCoreVersi { if (!SemanticVersion.TryParse(aspNetCoreVersionsFolder, out var aspNetCoreVersion)) { - throw new InvalidOperationException("Unable to parse version"); + throw new InvalidOperationException($"Unable to parse Asp.Net version {aspNetCoreVersionsFolder}"); } else { diff --git a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs index f8fd4293..f6f6962e 100644 --- a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs +++ b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs @@ -485,11 +485,6 @@ public void ShouldCompileAndExecuteWithWebSdk() { var processResult = ScriptTestRunner.Default.ExecuteFixture("WebApi", "--no-cache"); Assert.Equal(0, processResult.ExitCode); - - // var test = ScriptTestRunner.ExecuteFixtureInProcess("WebApi", "--no-cache --debug"); - // Assert.Equal(0, test); - // var (output, _) = ScriptTestRunner.Default.ExecuteFixture("CurrentContextualReflectionContext", "--isolated-load-context"); - // Assert.Contains("Dotnet.Script.Core.ScriptAssemblyLoadContext", output); } [Fact] From 75592d991ef6d14e08e99da6fb2f6350e51cc15c Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 25 Nov 2022 13:44:32 +0100 Subject: [PATCH 14/18] Removed Chocolatey and updated docker file --- build/Build.csx | 16 ---- build/Choco.csx | 92 -------------------- build/Chocolatey/tools/ChocolateyInstall.ps1 | 3 - build/Chocolatey/tools/LICENSE.TXT | 19 ---- build/Chocolatey/tools/VERIFICATION.TXT | 8 -- build/Dockerfile | 2 +- 6 files changed, 1 insertion(+), 139 deletions(-) delete mode 100644 build/Choco.csx delete mode 100644 build/Chocolatey/tools/ChocolateyInstall.ps1 delete mode 100644 build/Chocolatey/tools/LICENSE.TXT delete mode 100644 build/Chocolatey/tools/VERIFICATION.TXT diff --git a/build/Build.csx b/build/Build.csx index 623e404b..684f6602 100644 --- a/build/Build.csx +++ b/build/Build.csx @@ -1,7 +1,6 @@ #load "nuget:Dotnet.Build, 0.7.1" #load "nuget:dotnet-steps, 0.0.1" #load "nuget:github-changelog, 0.1.5" -#load "Choco.csx" #load "BuildContext.csx" using System.Xml.Linq; @@ -17,7 +16,6 @@ Step pack = () => { CreateGitHubReleaseAsset(); CreateNuGetPackages(); - CreateChocoPackage(); CreateGlobalToolPackage(); }; @@ -39,19 +37,6 @@ private void CreateGitHubReleaseAsset() Zip(publishArchiveFolder, pathToGitHubReleaseAsset); } - -private void CreateChocoPackage() -{ - if (BuildEnvironment.IsWindows) - { - Choco.Pack(dotnetScriptProjectFolder, publishArtifactsFolder, chocolateyArtifactsFolder); - } - else - { - Logger.Log("The choco package is only built on Windows"); - } -} - private void CreateGlobalToolPackage() { using var globalToolBuildFolder = new DisposableFolder(); @@ -102,7 +87,6 @@ private async Task PublishRelease() await ReleaseManagerFor(owner, projectName, BuildEnvironment.GitHubAccessToken) .CreateRelease(Git.Default.GetLatestTag(), pathToReleaseNotes, new[] { new ZipReleaseAsset(pathToGitHubReleaseAsset) }); NuGet.TryPush(nuGetArtifactsFolder); - Choco.TryPush(chocolateyArtifactsFolder, BuildEnvironment.ChocolateyApiKey); } } diff --git a/build/Choco.csx b/build/Choco.csx deleted file mode 100644 index 05c8de13..00000000 --- a/build/Choco.csx +++ /dev/null @@ -1,92 +0,0 @@ -#load "nuget:Dotnet.Build, 0.7.1" - -using System.Xml.Linq; - -public static class Choco -{ - /// - /// Creates a Chocolatey package based on a "csproj" project file. - /// - /// The path to the project folder. - /// The path to the output folder (*.nupkg) - public static void Pack(string pathToProjectFolder, string pathToBinaries, string outputFolder) - { - string pathToProjectFile = Directory.GetFiles(pathToProjectFolder, "*.csproj").Single(); - CreateSpecificationFromProject(pathToProjectFile, pathToBinaries); - Command.Execute("choco.exe", $@"pack {Path.Combine(FileUtils.GetScriptFolder(), "Chocolatey", "chocolatey.nuspec")} --outputdirectory {outputFolder}"); - } - - public static void Push(string packagesFolder, string apiKey, string source = "https://push.chocolatey.org/") - { - var packageFiles = Directory.GetFiles(packagesFolder, "*.nupkg"); - foreach (var packageFile in packageFiles) - { - Command.Execute("choco.exe", $"push {packageFile} --source {source} --key {apiKey}"); - } - } - - public static void TryPush(string packagesFolder, string apiKey, string source = "https://push.chocolatey.org/") - { - var packageFiles = Directory.GetFiles(packagesFolder, "*.nupkg"); - foreach (var packageFile in packageFiles) - { - Command.Execute("choco.exe", $"push {packageFile} --source {source} --key {apiKey}"); - } - } - - private static void CreateSpecificationFromProject(string pathToProjectFile, string pathToBinaries) - { - var projectFile = XDocument.Load(pathToProjectFile); - var authors = projectFile.Descendants("Authors").SingleOrDefault()?.Value; - var packageId = projectFile.Descendants("PackageId").SingleOrDefault()?.Value; - var description = projectFile.Descendants("Description").SingleOrDefault()?.Value; - var versionPrefix = projectFile.Descendants("VersionPrefix").SingleOrDefault()?.Value; - var versionSuffix = projectFile.Descendants("VersionSuffix").SingleOrDefault()?.Value; - - string version; - if (versionSuffix != null) - { - version = $"{versionPrefix}-{versionSuffix}"; - } - else - { - version = versionPrefix; - } - var iconUrl = projectFile.Descendants("PackageIconUrl").SingleOrDefault()?.Value; - var projectUrl = projectFile.Descendants("PackageProjectUrl").SingleOrDefault()?.Value; - var repositoryUrl = projectFile.Descendants("RepositoryUrl").SingleOrDefault()?.Value; - - var packageElement = new XElement("package"); - var metadataElement = new XElement("metadata"); - packageElement.Add(metadataElement); - - // Package id should be lower case - // https://chocolatey.org/docs/create-packages#naming-your-package - metadataElement.Add(new XElement("id", packageId.ToLower())); - metadataElement.Add(new XElement("version", version)); - metadataElement.Add(new XElement("authors", authors)); - metadataElement.Add(new XElement("licenseUrl", "https://licenses.nuget.org/MIT")); - metadataElement.Add(new XElement("projectUrl", projectUrl)); - metadataElement.Add(new XElement("iconUrl", iconUrl)); - metadataElement.Add(new XElement("description", description)); - metadataElement.Add(new XElement("tags", repositoryUrl)); - - var filesElement = new XElement("files"); - packageElement.Add(filesElement); - - // Add the tools folder that contains "ChocolateyInstall.ps1" - filesElement.Add(CreateFileElement(@"tools\*.*", $@"{packageId}\tools")); - var srcGlobPattern = $@"{pathToBinaries}\**\*"; - filesElement.Add(CreateFileElement(srcGlobPattern, packageId)); - using var fileStream = new FileStream(Path.Combine(FileUtils.GetScriptFolder(), "Chocolatey", "chocolatey.nuspec"), FileMode.Create); - new XDocument(packageElement).Save(fileStream); - } - - private static XElement CreateFileElement(string src, string target) - { - var srcAttribute = new XAttribute("src", src); - var targetAttribute = new XAttribute("target", target); - return new XElement("file", srcAttribute, targetAttribute); - } - -} \ No newline at end of file diff --git a/build/Chocolatey/tools/ChocolateyInstall.ps1 b/build/Chocolatey/tools/ChocolateyInstall.ps1 deleted file mode 100644 index 23b027f6..00000000 --- a/build/Chocolatey/tools/ChocolateyInstall.ps1 +++ /dev/null @@ -1,3 +0,0 @@ -# Add the binary folder to the users PATH environment variable. -$pathToBinaries = Join-Path -Path $($env:ChocolateyPackageFolder) -ChildPath $($env:ChocolateyPackageName ) -Install-ChocolateyPath -PathToInstall "$pathToBinaries" -PathType 'Machine' \ No newline at end of file diff --git a/build/Chocolatey/tools/LICENSE.TXT b/build/Chocolatey/tools/LICENSE.TXT deleted file mode 100644 index f8a5c9f2..00000000 --- a/build/Chocolatey/tools/LICENSE.TXT +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2019 dotnet-script - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/build/Chocolatey/tools/VERIFICATION.TXT b/build/Chocolatey/tools/VERIFICATION.TXT deleted file mode 100644 index 8835097c..00000000 --- a/build/Chocolatey/tools/VERIFICATION.TXT +++ /dev/null @@ -1,8 +0,0 @@ -VERIFICATION -Verification is intended to assist the Chocolatey moderators and community -in verifying that this package's contents are trustworthy. - -dotnet-script.dll : 3BF42E83BE931AC98D02306DBC6FB319 - -Check against the corresponding file in this release. -https://github.com/dotnet-script/dotnet-script/releases/download/0.13.0/dotnet-script.0.13.0.zip \ No newline at end of file diff --git a/build/Dockerfile b/build/Dockerfile index e6d29bc7..876d8d79 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/sdk:5.0 +FROM mcr.microsoft.com/dotnet/sdk:7.0 # https://www.nuget.org/packages/dotnet-script/ RUN dotnet tool install dotnet-script --tool-path /usr/bin From d28e921f0f88dda981ea49005da6b8f77aa08a2f Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 25 Nov 2022 14:05:25 +0100 Subject: [PATCH 15/18] Updated docs for specifying an SDK --- README.md | 40 +++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 724fdd59..02f3fb2d 100644 --- a/README.md +++ b/README.md @@ -8,19 +8,19 @@ Run C# scripts from the .NET CLI, define NuGet packages inline and edit/debug th ## NuGet Packages -| Name | Version | Framework(s) | -| ------------------------------------- | ------------------------------------------------------------ | -------------------------------- | -| `dotnet-script` (global tool) | [![Nuget](http://img.shields.io/nuget/v/dotnet-script.svg?maxAge=10800)](https://www.nuget.org/packages/dotnet-script/) | `net6.0`, `net5.0`, `netcoreapp3.1` | -| `Dotnet.Script` (CLI as Nuget) | [![Nuget](http://img.shields.io/nuget/v/dotnet.script.svg?maxAge=10800)](https://www.nuget.org/packages/dotnet.script/) | `net6.0`, `net5.0`, `netcoreapp3.1` | -| `Dotnet.Script.Core` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.Core.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.Core/) | `netcoreapp3.1` , `netstandard2.0` | -| `Dotnet.Script.DependencyModel` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.DependencyModel.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.DependencyModel/) | `netstandard2.0` | -| `Dotnet.Script.DependencyModel.Nuget` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.DependencyModel.Nuget.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.DependencyModel.Nuget/) | `netstandard2.0` | +| Name | Version | Framework(s) | +| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | +| `dotnet-script` (global tool) | [![Nuget](http://img.shields.io/nuget/v/dotnet-script.svg?maxAge=10800)](https://www.nuget.org/packages/dotnet-script/) | `net6.0`, `net5.0`, `netcoreapp3.1` | +| `Dotnet.Script` (CLI as Nuget) | [![Nuget](http://img.shields.io/nuget/v/dotnet.script.svg?maxAge=10800)](https://www.nuget.org/packages/dotnet.script/) | `net6.0`, `net5.0`, `netcoreapp3.1` | +| `Dotnet.Script.Core` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.Core.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.Core/) | `netcoreapp3.1` , `netstandard2.0` | +| `Dotnet.Script.DependencyModel` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.DependencyModel.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.DependencyModel/) | `netstandard2.0` | +| `Dotnet.Script.DependencyModel.Nuget` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.DependencyModel.Nuget.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.DependencyModel.Nuget/) | `netstandard2.0` | ## Installing ### Prerequisites -The only thing we need to install is [.NET Core 3.1 or .NET 5.0 SDK](https://www.microsoft.com/net/download/core). +The only thing we need to install is [.Net 6.0 or .Net 7.0](https://www.microsoft.com/net/download/core). ### .NET Core Global Tool @@ -52,11 +52,7 @@ Tool 'dotnet-script' (version '0.22.0') was successfully uninstalled. ### Windows -```powershell -choco install dotnet.script -``` - -We also provide a PowerShell script for installation. +PowerShell script for installation. ```powershell (new-object Net.WebClient).DownloadString("https://raw.githubusercontent.com/dotnet-script/dotnet-script/master/install/install.ps1") | iex @@ -569,6 +565,24 @@ We will also see this when working with scripts in VS Code under the problems pa ![image](https://user-images.githubusercontent.com/1034073/65727087-0e982600-e0b7-11e9-8fa0-d16331ab948a.png) +## Specifying an SDK + +Starting with `dotnet-script` 1.4.0 we can now specify the SDK to be used for a script. + +For instance, creating a web server in a script is now as simple as the following. + +```csharp +#r "sdk:Microsoft.NET.Sdk.Web" + +using Microsoft.AspNetCore.Builder; + +var a = WebApplication.Create(); +a.MapGet("/", () => "Hello world"); +a.Run(); +``` + +> Please note the the only SDK currently supported is `Microsoft.NET.Sdk.Web` + ## Team - [Bernhard Richter](https://github.com/seesharper) ([@bernhardrichter](https://twitter.com/bernhardrichter)) From bde2658f81434f90cd1c29bf59ae89f681803b7f Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 25 Nov 2022 20:19:32 +0100 Subject: [PATCH 16/18] Removed debug code in ScriptExecutionTests --- src/Dotnet.Script.Tests/ScriptExecutionTests.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs index f6f6962e..c8947d33 100644 --- a/src/Dotnet.Script.Tests/ScriptExecutionTests.cs +++ b/src/Dotnet.Script.Tests/ScriptExecutionTests.cs @@ -21,9 +21,8 @@ public ScriptExecutionTests(ITestOutputHelper testOutputHelper) [Fact] public void ShouldExecuteHelloWorld() { - ScriptTestRunner.ExecuteFixtureInProcess("HelloWorld", "--no-cache"); - // var (output, _) = ScriptTestRunner.Default.ExecuteFixture("HelloWorld", "--no-cache"); - // Assert.Contains("Hello World", output); + var (output, _) = ScriptTestRunner.Default.ExecuteFixture("HelloWorld", "--no-cache"); + Assert.Contains("Hello World", output); } [Fact] From 69feacad708a1fdf381daea6d8a1dee8d1a9e62e Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 25 Nov 2022 20:26:51 +0100 Subject: [PATCH 17/18] Added a comment on default usings --- src/Dotnet.Script.Core/ScriptCompiler.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Dotnet.Script.Core/ScriptCompiler.cs b/src/Dotnet.Script.Core/ScriptCompiler.cs index 459f1603..2cfdab5e 100644 --- a/src/Dotnet.Script.Core/ScriptCompiler.cs +++ b/src/Dotnet.Script.Core/ScriptCompiler.cs @@ -39,6 +39,7 @@ static ScriptCompiler() }); } + //Note: We should set this according to the SDK being used protected virtual IEnumerable ImportedNamespaces => new[] { "System", @@ -94,7 +95,7 @@ public virtual ScriptOptions CreateScriptOptions(ScriptContext context, IList rdt.Name, rdt => rdt.Scripts); var opts = ScriptOptions.Default.AddImports(ImportedNamespaces) - .WithSourceResolver(new NuGetSourceReferenceResolver(new SourceFileResolver(ImmutableArray.Empty, context.WorkingDirectory),scriptMap)) + .WithSourceResolver(new NuGetSourceReferenceResolver(new SourceFileResolver(ImmutableArray.Empty, context.WorkingDirectory), scriptMap)) .WithMetadataResolver(new NuGetMetadataReferenceResolver(ScriptMetadataResolver.Default.WithBaseDirectory(context.WorkingDirectory))) .WithEmitDebugInformation(true) .WithLanguageVersion(LanguageVersion.Preview) @@ -200,7 +201,7 @@ AssemblyLoadContext is not ScriptAssemblyLoadContext salc || Assembly loadedAssembly = null; if (homogenization) loadedAssembliesMap.TryGetValue(runtimeAssembly.Name.Name, out loadedAssembly); - + if (loadedAssembly == null) { _logger.Trace("Adding reference to a runtime dependency => " + runtimeAssembly); @@ -290,7 +291,7 @@ private Assembly MapUnresolvedAssemblyToRuntimeLibrary(IDictionary assemblyName.Version) { loadedAssemblyMap.TryGetValue(assemblyName.Name, out var loadedAssembly); - if(loadedAssembly != null) + if (loadedAssembly != null) { _logger.Trace($"Redirecting {assemblyName} to already loaded {loadedAssembly.GetName().Name}"); return loadedAssembly; From df23881fe63430cfc3fe3316900ae5061d1eb038 Mon Sep 17 00:00:00 2001 From: Bernhard Richter Date: Fri, 25 Nov 2022 20:31:27 +0100 Subject: [PATCH 18/18] Fixed version information in docs --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 02f3fb2d..27e2cc13 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,13 @@ Run C# scripts from the .NET CLI, define NuGet packages inline and edit/debug th ## NuGet Packages -| Name | Version | Framework(s) | -| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | -| `dotnet-script` (global tool) | [![Nuget](http://img.shields.io/nuget/v/dotnet-script.svg?maxAge=10800)](https://www.nuget.org/packages/dotnet-script/) | `net6.0`, `net5.0`, `netcoreapp3.1` | -| `Dotnet.Script` (CLI as Nuget) | [![Nuget](http://img.shields.io/nuget/v/dotnet.script.svg?maxAge=10800)](https://www.nuget.org/packages/dotnet.script/) | `net6.0`, `net5.0`, `netcoreapp3.1` | -| `Dotnet.Script.Core` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.Core.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.Core/) | `netcoreapp3.1` , `netstandard2.0` | -| `Dotnet.Script.DependencyModel` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.DependencyModel.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.DependencyModel/) | `netstandard2.0` | -| `Dotnet.Script.DependencyModel.Nuget` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.DependencyModel.Nuget.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.DependencyModel.Nuget/) | `netstandard2.0` | +| Name | Version | Framework(s) | +| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | +| `dotnet-script` (global tool) | [![Nuget](http://img.shields.io/nuget/v/dotnet-script.svg?maxAge=10800)](https://www.nuget.org/packages/dotnet-script/) | `net6.0`, `net7.0` | +| `Dotnet.Script` (CLI as Nuget) | [![Nuget](http://img.shields.io/nuget/v/dotnet.script.svg?maxAge=10800)](https://www.nuget.org/packages/dotnet.script/) | `net6.0`, `net7.0` | +| `Dotnet.Script.Core` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.Core.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.Core/) | `net6.0` , `netstandard2.0` | +| `Dotnet.Script.DependencyModel` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.DependencyModel.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.DependencyModel/) | `netstandard2.0` | +| `Dotnet.Script.DependencyModel.Nuget` | [![Nuget](http://img.shields.io/nuget/v/Dotnet.Script.DependencyModel.Nuget.svg?maxAge=10800)](https://www.nuget.org/packages/Dotnet.Script.DependencyModel.Nuget/) | `netstandard2.0` | ## Installing