8000 Merge branch 'master' into netcoreapp5.0 · dotnet-script/dotnet-script@bd4a42b · GitHub
[go: up one dir, main page]

Skip to content

Commit bd4a42b

Browse files
committed
Merge branch 'master' into netcoreapp5.0
2 parents 2919073 + f4ea82a commit bd4a42b

28 files changed

+208
-94
lines changed

README.md

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ Dotnet-Script can create a standalone executable or DLL for your script.
243243
| -d | --debug | Enables debug output. |
244244
| -r | --runtime | The runtime used when publishing the self contained executable. Defaults to your current runtime. |
245245

246-
The executable you can run directly independent of dotnet install, while the DLL is can be run using the dotnet CLI like this:
246+
The executable you can run directly independent of dotnet install, while the DLL can be run using the dotnet CLI like this:
247247

248248
```shell
249249
dotnet script exec {path_to_dll} -- arg1 arg2
@@ -264,6 +264,15 @@ In order to execute a script it needs to be compiled first and since that is a C
264264

265265
> You can override this automatic caching by passing **--no-cache** flag, which will bypass both caches and cause dependency resolution and script compilation to happen every time we execute the script.
266266
267+
#### Cache Location
268+
269+
The temporary location used for caches is a sub-directory named `dotnet-script` under (in order of priority):
270+
271+
1. The path specified for the value of the environment variable named `DOTNET_SCRIPT_CACHE_LOCATION`, if defined and value is not empty.
272+
2. Linux distributions only: `$XDG_CACHE_HOME` if defined otherwise `$HOME/.cache`
273+
3. macOS only: `~/Library/Caches`
274+
4. The value returned by [`Path.GetTempPath`](https://docs.microsoft.com/en-us/dotnet/api/system.io.path.gettemppath) for the platform.
275+
267276
###
268277

269278
### Debugging
@@ -484,7 +493,7 @@ The first thing we need to do add the following to the `launch.config` file that
484493
}
485494
```
486495

487-
To debug this script we need a way to attach the debugger in VS Code and to the simplest thing we can do here is to wait for the debugger to attach by adding this method somewhere.
496+
To debug this script we need a way to attach the debugger in VS Code and the simplest thing we can do here is to wait for the debugger to attach by adding this method somewhere.
488497

489498
```c#
490499
public static void WaitForDebugger()
@@ -515,7 +524,7 @@ Attach Debugger (VS Code)
515524

516525
This now gives us a chance to attach the debugger before stepping into the script and from VS Code, select the `.NET Core Attach` debugger and pick the process that represents the executing script.
517526

518-
Once that is done we should see out breakpoint being hit.
527+
Once that is done we should see our breakpoint being hit.
519528

520529
## Configuration(Debug/Release)
521530

build/Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
FROM mcr.microsoft.com/dotnet/core/sdk:3.0
1+
FROM mcr.microsoft.com/dotnet/core/sdk:3.1
22

33
# https://www.nuget.org/packages/dotnet-script/
44
RUN dotnet tool install dotnet-script --tool-path /usr/bin

global.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"sdk": {
3+
"version": "3.1.102",
4+
"rollForward": "latestFeature"
5+
}
6+
}

src/Dotnet.Script.Core/Commands/ExecuteScriptCommand.cs

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -49,28 +49,21 @@ private string GetLibrary(ExecuteScriptCommandOptions executeOptions)
4949
var executionCacheFolder = Path.Combine(projectFolder, "execution-cache");
5050
var pathToLibrary = Path.Combine(executionCacheFolder, "script.dll");
5151

52-
if (!TryCreateHash(executeOptions, out var hash) || !TryGetHash(executionCacheFolder, out var cachedHash))
52+
if (TryCreateHash(executeOptions, out var hash)
53+
&& TryGetHash(executionCacheFolder, out var cachedHash)
54+
&& string.Equals(hash, cachedHash))
5355
{
54-
return CreateLibrary();
56+
_logger.Debug($"Using cached compilation: " + pathToLibrary);
57+
return pathToLibrary;
5558
}
5659

57-
if (!string.Equals(hash, cachedHash))
60+
var options = new PublishCommandOptions(executeOptions.File, executionCacheFolder, "script", PublishType.Library, executeOptions.OptimizationLevel, executeOptions.PackageSources, null, executeOptions.NoCache);
61+
new PublishCommand(_scriptConsole, _logFactory).Execute(options);
62+
if (hash != null)
5863
{
59-
return CreateLibrary();
60-
}
61-
62-
return pathToLibrary;
63-
64-
string CreateLibrary()
65-
{
66-
var options = new PublishCommandOptions(executeOptions.File, executionCacheFolder, "script", PublishType.Library, executeOptions.OptimizationLevel, executeOptions.PackageSources, null, executeOptions.NoCache);
67-
new PublishCommand(_scriptConsole, _logFactory).Execute(options);
68-
if (hash != null)
69-
{
70-
File.WriteAllText(Path.Combine(executionCacheFolder, "script.sha256"), hash);
71-
}
72-
return Path.Combine(executionCacheFolder, "script.dll");
64+
File.WriteAllText(Path.Combine(executionCacheFolder, "script.sha256"), hash);
7365
}
66+
return Path.Combine(executionCacheFolder, "script.dll");
7467
}
7568

7669
public bool TryCreateHash(ExecuteScriptCommandOptions options, out string hash)

src/Dotnet.Script.Core/Dotnet.Script.Core.csproj

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
2-
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project Sdk="Microsoft.NET.Sdk">
33
<PropertyGroup>
44
<Description>A cross platform library allowing you to run C# (CSX) scripts with support for debugging and inline NuGet packages. Based on Roslyn.</Description>
5-
<VersionPrefix>0.51.0</VersionPrefix>
5+
<VersionPrefix>0.53.0</VersionPrefix>
66
<Authors>filipw</Authors>
77
<TargetFrameworks>netstandard2.0</TargetFrameworks>
88
<AssemblyName>Dotnet.Script.Core</AssemblyName>
@@ -17,28 +17,24 @@
1717
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
1818
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
1919
</PropertyGroup>
20-
2120
<ItemGroup>
2221
<EmbeddedResource Include="**/*.template" />
2322
</ItemGroup>
24-
2523
<ItemGroup>
26-
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="3.4.0" />
27-
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
24+
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="3.7.0" />
25+
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
2826
<PackageReference Include="ReadLine" Version="2.0.1" />
2927
<PackageReference Include="System.Collections.Immutable" Version="1.5.0" />
3028
<PackageReference Include="System.Reflection.Metadata" Version="1.6.0" />
3129
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
3230
<!-- The following references are just quick fixes for issue #166 and issue #268
3331
We need to figure out why we can't load these via the dependency context.
3432
-->
35-
<PackageReference Include="System.Configuration.ConfigurationManager" Version="4.5.0" />
36-
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" />
33+
<PackageReference Include="System.Configuration.ConfigurationManager" Version="4.7.0" />
34+
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.7.1" />
3735
</ItemGroup>
38-
3936
<ItemGroup>
4037
<ProjectReference Include="..\Dotnet.Script.DependencyModel.Nuget\Dotnet.Script.DependencyModel.NuGet.csproj" />
4138
<ProjectReference Include="..\Dotnet.Script.DependencyModel\Dotnet.Script.DependencyModel.csproj" />
4239
</ItemGroup>
43-
4440
</Project>

src/Dotnet.Script.Core/ScriptDownloader.cs

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
using System;
22
using System.IO;
3+
using System.IO.Compression;
34
using System.Net.Http;
4-
using System.Net.Mime;
55
using System.Threading.Tasks;
66

77
namespace Dotnet.Script.Core
@@ -10,23 +10,30 @@ public class ScriptDownloader
1010
{
1111
public async Task<string> Download(string uri)
1212
{
13-
const string plainTextMediaType = "text/plain";
1413
using (HttpClient client = new HttpClient())
1514
{
16-
using (HttpResponseMessage response = await client.GetAsync(uri))
15+
using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
1716
{
1817
response.EnsureSuccessStatusCode();
1918

2019
using (HttpContent content = response.Content)
2120
{
22-
string mediaType = content.Headers.ContentType.MediaType;
23-
24-
if (string.IsNullOrWhiteSpace(mediaType) || mediaType.Equals(plainTextMediaType, StringComparison.InvariantCultureIgnoreCase))
21+
var mediaType = content.Headers.ContentType.MediaType?.ToLowerInvariant().Trim();
22+
switch (mediaType)
2523
{
26-
return await content.ReadAsStringAsync();
24+
case null:
25+
case "":
26+
case "text/plain":
27+
return await content.ReadAsStringAsync();
28+
case "application/gzip":
29+
case "application/x-gzip":
30+
using (var stream = await content.ReadAsStreamAsync())
31+
using (var gzip = new GZipStream(stream, CompressionMode.Decompress))
32+
using (var reader = new StreamReader(gzip))
33+
return await reader.ReadToEndAsync();
34+
default:
35+
throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https");
2736
}
28-
29-
throw new NotSupportedException($"The media type '{mediaType}' is not supported when executing a script over http/https");
3037
}
3138
}
3239
}

src/Dotnet.Script.Core/ScriptPublisher.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ public void CreateExecutable<TReturn, THost>(ScriptContext context, LogFactory l
8888

8989
var commandRunner = new CommandRunner(logFactory);
9090
// todo: may want to add ability to return dotnet.exe errors
91-
var exitcode = commandRunner.Execute("dotnet", $"publish \"{renamedProjectPath}\" -c Release -r {runtimeIdentifier} -o \"{context.WorkingDirectory}\" {(ScriptEnvironment.Default.TargetFramework == "netcoreapp3.0" ? "/p:PublishSingleFile=true" : "")} /p:DebugType=Embedded");
91+
var exitcode = commandRunner.Execute("dotnet", $"publish \"{renamedProjectPath}\" -c Release -r {runtimeIdentifier} -o \"{context.WorkingDirectory}\" {(ScriptEnvironment.Default.NetCoreVersion.Major >= 3 ? "/p:PublishSingleFile=true" : string.Empty)} /p:DebugType=Embedded");
9292

9393
if (exitcode != 0)
9494
{

src/Dotnet.Script.Core/ScriptRunner.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,9 @@ public async Task<TReturn> Execute<TReturn>(string dllPath, IEnumerable<string>
4747
submissionStates[0] = globals;
4848

4949
var resultTask = method.Invoke(null, new[] { submissionStates }) as Task<TReturn>;
50-
TReturn returnValue;
5150
try
5251
{
53-
returnValue = await resultTask;
52+
_ = await resultTask;
5453
}
5554
catch (System.Exception ex)
5655
{

src/Dotnet.Script.DependencyModel.Nuget/Dotnet.Script.DependencyModel.NuGet.csproj

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,17 @@
88
<RepositoryUrl>https://github.com/filipw/dotnet-script.git</RepositoryUrl>
99
<RepositoryType>git</RepositoryType>
1010
<PackageTags>script;csx;csharp;roslyn;nuget</PackageTags>
11-
<Version>0.51.0</Version>
11+
<Version>0.53.0</Version>
1212
<Description>A MetadataReferenceResolver that allows inline nuget references to be specified in script(csx) files.</Description>
1313
<Authors>dotnet-script</Authors>
1414
<Company>dotnet-script</Company>
15+
<LangVersion>latest</LangVersion>
1516
</PropertyGroup>
17+
18+
<ItemGroup>
19+
<Compile Include="..\Dotnet.Script.DependencyModel\ProjectSystem\ScriptParserInternal.cs" Link="ScriptParserInternal.cs" />
20+
</ItemGroup>
1621
<ItemGroup>
17-
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="3.4.0" />
22+
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="3.7.0" />
1823
</ItemGroup>
1924
</Project>

src/Dotnet.Script.DependencyModel.Nuget/NuGetSourceReferenceResolver.cs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
11
using System;
22
using System.Collections.Generic;
3-
using System.Diagnostics;
43
using System.IO;
5-
using System.Text.RegularExpressions;
64
using Microsoft.CodeAnalysis;
5+
using Dotnet.Script.DependencyModel.ProjectSystem;
76

87
namespace Dotnet.Script.DependencyModel.NuGet
98
{
@@ -15,7 +14,6 @@ public class NuGetSourceReferenceResolver : SourceReferenceResolver
1514
{
1615
private readonly SourceReferenceResolver _sourceReferenceResolver;
1716
private readonly IDictionary<string, IReadOnlyList<string>> _scriptMap;
18-
private static readonly Regex PackageNameMatcher = new Regex(@"\s*nuget\s*:\s*(.*)\s*,", RegexOptions.Compiled | RegexOptions.IgnoreCase);
1917

2018
public NuGetSourceReferenceResolver(SourceReferenceResolver sourceReferenceResolver, IDictionary<string, IReadOnlyList<string>> scriptMap)
2119
{
@@ -48,9 +46,8 @@ public override string NormalizePath(string path, string baseFilePath)
4846

4947
public override string ResolveReference(string path, string baseFilePath)
5048
{
51-
if (path.StartsWith("nuget:", StringComparison.OrdinalIgnoreCase))
49+
if (ScriptParser.TryParseNuGetPackageReference(path, out var packageName, out _))
5250
{
53-
var packageName = PackageNameMatcher.Match(path).Groups[1].Value;
5451
if (_scriptMap.TryGetValue(packageName, out var scripts))
5552
{
5653
if (scripts.Count == 1)
@@ -66,9 +63,8 @@ public override string ResolveReference(string path, string baseFilePath)
6663

6764
public override Stream OpenRead(string resolvedPath)
6865
{
69-
if (resolvedPath.StartsWith("nuget:", StringComparison.OrdinalIgnoreCase))
66+
if (ScriptParser.TryParseNuGetPackageReference(resolvedPath, out var packageName, out _))
7067
{
71-
var packageName = PackageNameMatcher.Match(resolvedPath).Groups[1].Value;
7268
var scripts = _scriptMap[packageName];
7369
if (scripts.Count == 1)
7470
{

src/Dotnet.Script.DependencyModel/Context/DotnetRestorer.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Dotnet.Script.DependencyModel.Process;
44
using Dotnet.Script.DependencyModel.ProjectSystem;
55
using System;
6+
using System.IO;
67
using System.Linq;
78

89
namespace Dotnet.Script.DependencyModel.Context
@@ -25,9 +26,12 @@ public void Restore(ProjectFileInfo projectFileInfo, string[] packageSources)
2526
var packageSourcesArgument = CreatePackageSourcesArguments();
2627
var configFileArgument = CreateConfigFileArgument();
2728
var runtimeIdentifier = _scriptEnvironment.RuntimeIdentifier;
29+
var workingDirectory = Path.GetFullPath(Path.GetDirectoryName(projectFileInfo.Path));
30+
2831

2932
_logger.Debug($"Restoring {projectFileInfo.Path} using the dotnet cli. RuntimeIdentifier : {runtimeIdentifier} NugetConfigFile: {projectFileInfo.NuGetConfigFile}");
30-
var exitcode = _commandRunner.Execute("dotnet", $"restore \"{projectFileInfo.Path}\" -r D7AE {runtimeIdentifier} {packageSourcesArgument} {configFileArgument}");
33+
34+
var exitcode = _commandRunner.Execute("dotnet", $"restore \"{projectFileInfo.Path}\" -r {runtimeIdentifier} {packageSourcesArgument} {configFileArgument}", workingDirectory);
3135
if (exitcode != 0)
3236
{
3337
// We must throw here, otherwise we may incorrectly run with the old 'project.assets.json'

src/Dotnet.Script.DependencyModel/Context/ScriptDependencyContextReader.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile)
6060
}
6161
}
6262

63-
if (ScriptEnvironment.Default.NetCoreVersion.Version.StartsWith("3") || ScriptEnvironment.Default.NetCoreVersion.Version.StartsWith("5"))
63+
if (ScriptEnvironment.Default.NetCoreVersion.Major >= 3)
6464
{
6565
var netcoreAppRuntimeAssemblyLocation = Path.GetDirectoryName(typeof(object).Assembly.Location);
6666
var netcoreAppRuntimeAssemblies = Directory.GetFiles(netcoreAppRuntimeAssemblyLocation, "*.dll").Where(IsAssembly).ToArray();

src/Dotnet.Script.DependencyModel/Dotnet.Script.DependencyModel.csproj

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,27 @@
1111
<RepositoryUrl>https://github.com/filipw/dotnet-script.git</RepositoryUrl>
1212
<RepositoryType>git</RepositoryType>
1313
<PackageTags>script;csx;csharp;roslyn;omnisharp</PackageTags>
14-
<Version>0.51.0</Version>
14+
<Version>0.53.0</Version>
1515
<LangVersion>latest</LangVersion>
1616
</PropertyGroup>
1717

1818
<ItemGroup>
1919
<None Remove="NuGet\NuGet430.exe" />
2020
</ItemGroup>
2121

22+
<ItemGroup>
23+
<Compile Update="ProjectSystem\ScriptParserInternal.cs">
24+
<DependentUpon>ScriptParser.cs</DependentUpon>
25+
</Compile>
26+
</ItemGroup>
27+
2228
<ItemGroup>
2329
<EmbeddedResource Include="ProjectSystem\csproj.template" />
2430
</ItemGroup>
2531

2632
<ItemGroup>
2733
<PackageReference Include="NuGet.ProjectModel" Version="5.2.0" />
28-
<PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="3.1.0" />
34+
<PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="3.1.6" />
2935
</ItemGroup>
3036

3137
</Project>

src/Dotnet.Script.DependencyModel/Environment/ScriptEnvironment.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ private static DotnetVersion GetNetCoreAppVersion()
7676
{
7777
// https://github.com/dotnet/BenchmarkDotNet/blob/94863ab4d024eca04d061423e5aad498feff386b/src/BenchmarkDotNet/Portability/RuntimeInformation.cs#L156
7878
var codeBase = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly.CodeBase;
79-
var pattern = @"^.*Microsoft\.NETCore\.App\/(\d\.\d)(.*?)\/";
79+
var pattern = @"^.*Microsoft\.NETCore\.App\/(\d+\.\d+)(.*?)\/";
8080
var match = Regex.Match(codeBase, pattern, RegexOptions.IgnoreCase);
8181
if (!match.Success)
8282
{
@@ -139,9 +139,17 @@ public DotnetVersion(string version, string tfm)
139139
{
140140
Version = version;
141141
Tfm = tfm;
142+
143+
var versionMatch = Regex.Match(input: Version, pattern: @"^(\d+)(?:\.(\d+))?");
144+
if (versionMatch.Success && versionMatch.Groups[1].Success)
145+
Major = int.Parse(versionMatch.Groups[1].Value);
146+
if (versionMatch.Success && versionMatch.Groups[2].Success)
147+
Minor = int.Parse(versionMatch.Groups[2].Value);
142148
}
143149

144150
public string Version { get; }
145151
public string Tfm { get; }
152+
public int Major { get; }
153+
public int Minor { get; }
146154
}
147155
}

src/Dotnet.Script.DependencyModel/ProjectSystem/PackageVersion.cs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,38 @@ namespace Dotnet.Script.DependencyModel.ProjectSystem
88
/// </summary>
99
public class PackageVersion : IEquatable<PackageVersion>
1010
{
11-
private static readonly Regex IsPinnedRegex = new Regex(@"^(?>\[\d+[^,\]]+(?<!\.)\]|\d+(\.\d+){2,})$", RegexOptions.Compiled);
11+
// Following patterns are "inspired" from SemVer 2.0 grammar:
12+
//
13+
// Source: https://semver.org/spec/v2.0.0.html#backusnaur-form-grammar-for-valid-semver-versions
14+
15+
// <numeric identifier> ::= "0"
16+
// | <positive digit>
17+
// | <positive digit> <digits>
18+
//
19+
// <digits> ::= <digit>
20+
// | <digit> <digits>
21+
//
22+
// <digit> ::= "0"
23+
// | <positive digit>
24+
//
25+
// <positive digit> ::= "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
26+
27+
const string NumericPattern = @"(?:0|[1-9][0-9]*)";
28+
29+
// <valid semver> ::= <version core>
30+
// | <version core> "-" <pre-release>
31+
// | <version core> "+" <build>
32+
// | <version core> "-" <pre-release> "+" <build>
33+
//
34+
// <version core> ::= <major> "." <minor> "." <patch>
35+
36+
const string MajorPlusVersionPattern = NumericPattern + @"(?:\." + NumericPattern + @")";
37+
const string VersionSuffixPattern = @"(?:[+-][\w][\w+.-]*)?";
38+
39+
private static readonly Regex IsPinnedRegex =
40+
new Regex(@"^(?>\[" + MajorPlusVersionPattern + @"{1,4}" + VersionSuffixPattern + @"\]"
41+
+ @"|" + MajorPlusVersionPattern + @"{2,3}" + VersionSuffixPattern + @")$",
42+
RegexOptions.Compiled);
1243

1344
/// <summary>
1445
/// Initializes a new instance of the <see cref="PackageVersion"/> class.

0 commit comments

Comments
 (0)
0