From af2381e9776f1baf0d05fe02b9eee8ec835cba66 Mon Sep 17 00:00:00 2001 From: dev Date: Tue, 7 Jan 2020 07:38:49 +0100 Subject: [PATCH 01/43] Added ScriptPath properties to Script class in templates --- Program.cs | 15 +++++++++------ Templates/Script.csx | 6 ++++++ Templates/ScriptUI.csx | 8 ++++++++ 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/Program.cs b/Program.cs index 3813de3..6125e2d 100644 --- a/Program.cs +++ b/Program.cs @@ -158,7 +158,6 @@ static bool TryGetCache(string assemblyFile, string hashFile, string configFile, static IDictionary ParseArguments(IEnumerable args) { var arguments = new Dictionary(); - arguments["ThisScriptPath"] = Path.GetFullPath(args.First()); string key = null; foreach (var value in args.Skip(1)) { @@ -186,11 +185,15 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st config = null; var lines = File.ReadAllLines(scriptFile); Console.WriteLine($"Compiling script {scriptFile}..."); - var compilation = CSharpScript.Create(string.Join(Environment.NewLine, lines), ScriptOptions.Default.WithEmitDebugInformation(true), typeof(ScriptGlobals)).GetCompilation(); + var options = ScriptOptions.Default + .WithEmitDebugInformation(true) + .WithFilePath(scriptFile) + ; + var compilation = CSharpScript.Create(string.Join(Environment.NewLine, lines), options, typeof(ScriptGlobals)).GetCompilation(); var result = compilation.Emit(assemblyFile); PrintCompilationDiagnostics(result, lines); if (!result.Success) - { + { System.Threading.Thread.Sleep(5000); return false; } @@ -242,9 +245,9 @@ static void RunScript(string[] args) Console.ResetColor(); } } - + LoadPackages(scriptPath); - + var cacheFileBase = GetCacheFilenameBase(scriptPath); var assemblyFile = cacheFileBase + ".dll"; var hashFile = cacheFileBase + ".hash"; @@ -309,7 +312,7 @@ static void CreateNew(string template) { var templates = typeof(Program).Assembly.GetManifestResourceNames() .ToDictionary(x => Path.GetExtension(Path.GetFileNameWithoutExtension(x)).Substring(1), StringComparer.OrdinalIgnoreCase); - + if (template == null) { Console.Write("Available templates: "); diff --git a/Templates/Script.csx b/Templates/Script.csx index 41b92f2..5575c89 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -17,6 +17,7 @@ using System; using System.Collections.Generic; +Script.WriteLine($"Executing script '{Script.ScriptPath}'...", ConsoleColor.Green); Script.WriteLine("Hallo from script"); Script.WriteLine("Arguments:"); @@ -30,6 +31,11 @@ Console.ReadLine(); public static class Script { + static string GetScriptPath([System.Runtime.CompilerServices.CallerFilePath] string path = null) => path; + public static string ScriptPath { get; } = GetScriptPath(); + public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath); + public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath); + static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; [System.Runtime.InteropServices.DllImport("user32.dll")] diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index 4618354..11ee8d4 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -33,6 +33,9 @@ using System.Runtime.CompilerServices; // Script.HideConsole(); +Script.WriteLine($"Executing script '{Script.ScriptPath}'...", ConsoleColor.Green); +Script.WriteLine("Hallo from script"); + Script.WriteLine("Arguments:"); Script.WriteLines(Args.Select(x => $"{x.Key}: {x.Value}")); @@ -53,6 +56,11 @@ window.ShowDialog(); public static class Script { + static string GetScriptPath([System.Runtime.CompilerServices.CallerFilePath] string path = null) => path; + public static string ScriptPath { get; } = GetScriptPath(); + public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath); + public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath); + static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; [System.Runtime.InteropServices.DllImport("user32.dll")] From 8f7288daa094dacdcb112890eb1b71bc8d9839df Mon Sep 17 00:00:00 2001 From: dev Date: Tue, 7 Jan 2020 07:50:40 +0100 Subject: [PATCH 02/43] Breaking change: Args is now passed as string[] to the script --- Program.cs | 34 ++++------------------------------ Templates/Script.csx | 32 +++++++++++++++++++++++++++++--- Templates/ScriptUI.csx | 32 +++++++++++++++++++++++++++++--- 3 files changed, 62 insertions(+), 36 deletions(-) diff --git a/Program.cs b/Program.cs index 6125e2d..d737531 100644 --- a/Program.cs +++ b/Program.cs @@ -21,9 +21,9 @@ namespace CSharpScriptRunner { public sealed class ScriptGlobals { - public IReadOnlyDictionary Args { get; } + public string[] Args { get; } - internal ScriptGlobals(IDictionary args) => Args = new ReadOnlyDictionary(args); + internal ScriptGlobals(string[] args) => Args = args; } static class Program @@ -155,31 +155,6 @@ static bool TryGetCache(string assemblyFile, string hashFile, string configFile, return true; } - static IDictionary ParseArguments(IEnumerable args) - { - var arguments = new Dictionary(); - string key = null; - foreach (var value in args.Skip(1)) - { - if (value.StartsWith("-")) - { - if (key != null) - arguments[key] = true.ToString(); - key = value.Substring(1); - } - else - { - if (key == null) - throw new ArgumentNullException(value, "The parameter is missing its name."); - arguments[key] = value; - key = null; - } - } - if (key != null) - arguments[key] = true.ToString(); - return arguments; - } - static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, string configFile, byte[] scriptHash, out Config config) { config = null; @@ -267,10 +242,9 @@ static void RunScript(string[] args) var entryPoint = type.GetMethod(config.Method, BindingFlags.Static | BindingFlags.Public); if (entryPoint == null) return; - - var arguments = ParseArguments(args); + Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath); - var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(arguments), null } }); + var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), null } }); task.Wait(); } diff --git a/Templates/Script.csx b/Templates/Script.csx index 5575c89..481569d 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -1,8 +1,9 @@ // Run with CSharpScriptRunner: https://github.com/ArgusMagnus/CSharpScriptRunner/releases // // Arguments: -// Arguments are received in the global variable 'Args' which is of type 'IReadOnlyDictionary'. -// Arguments are passed to the script in the format "-argName argValue". When no 'argValue' is specified, +// Arguments are received in the global variable 'Args' which is of type 'string[]'. +// The Script.ParseArguments method expects that the arguments were passed to +// the script in the format "-argName argValue". When no 'argValue' is specified, // the value is assumed to be "True". // Example: CSharpScriptRunner.exe Script.csx -switch1 -arg1 Hello -arg2 World // @@ -21,7 +22,7 @@ Script.WriteLine($"Executing script '{Script.ScriptPath}'...", ConsoleColor.Gree Script.WriteLine("Hallo from script"); Script.WriteLine("Arguments:"); -foreach (var arg in Args) +foreach (var arg in Script.ParseArguments(Args)) Script.WriteLine($"{arg.Key}: {arg.Value}"); Script.WriteLine("Press Enter to exit"); @@ -75,6 +76,31 @@ public static class Script Console.Write(text); Console.ForegroundColor = c; } + + public static IDictionary ParseArguments(IEnumerable args) + { + var arguments = new Dictionary(); + string key = null; + foreach (var value in args) + { + if (value.StartsWith("-")) + { + if (key != null) + arguments[key] = true.ToString(); + key = value.Substring(1); + } + else + { + if (key == null) + throw new ArgumentNullException(value, "The parameter is missing its name."); + arguments[key] = value; + key = null; + } + } + if (key != null) + arguments[key] = true.ToString(); + return arguments; + } } #endregion \ No newline at end of file diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index 11ee8d4..b2760e8 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -1,8 +1,9 @@ // Run with CSharpScriptRunner: https://github.com/ArgusMagnus/CSharpScriptRunner/releases // // Arguments: -// Arguments are received in the global variable 'Args' which is of type 'IReadOnlyDictionary'. -// Arguments are passed to the script in the format "-argName argValue". When no 'argValue' is specified, +// Arguments are received in the global variable 'Args' which is of type 'string[]'. +// The Script.ParseArguments method expects that the arguments were passed to +// the script in the format "-argName argValue". When no 'argValue' is specified, // the value is assumed to be "True". // Example: CSharpScriptRunner.exe Script.csx -switch1 -arg1 Hello -arg2 World // @@ -37,7 +38,7 @@ Script.WriteLine($"Executing script '{Script.ScriptPath}'...", ConsoleColor.Gree Script.WriteLine("Hallo from script"); Script.WriteLine("Arguments:"); -Script.WriteLines(Args.Select(x => $"{x.Key}: {x.Value}")); +Script.WriteLines(Script.ParseArguments(Args).Select(x => $"{x.Key}: {x.Value}")); var window = (Window)XamlReader.Parse(@" ParseArguments(IEnumerable args) + { + var arguments = new Dictionary(); + string key = null; + foreach (var value in args) + { + if (value.StartsWith("-")) + { + if (key != null) + arguments[key] = true.ToString(); + key = value.Substring(1); + } + else + { + if (key == null) + throw new ArgumentNullException(value, "The parameter is missing its name."); + arguments[key] = value; + key = null; + } + } + if (key != null) + arguments[key] = true.ToString(); + return arguments; + } } #region WPF utility classes From 7f1d86783af094fda52d122ed9c88cb0fa1e10c9 Mon Sep 17 00:00:00 2001 From: dev Date: Tue, 7 Jan 2020 12:22:38 +0100 Subject: [PATCH 03/43] Breaking change: Changed NuGet reference syntax to be in line with other implementations --- NuGet.cs | 18 ++++++------------ Program.cs | 23 ++++++++++++++++------- Templates/Script.csx | 6 +++--- Templates/ScriptUI.csx | 6 +++--- 4 files changed, 28 insertions(+), 25 deletions(-) diff --git a/NuGet.cs b/NuGet.cs index d0c18e5..0e1b26d 100644 --- a/NuGet.cs +++ b/NuGet.cs @@ -20,13 +20,13 @@ namespace CSharpScriptRunner { static class NuGet { - public static async Task LoadPackage(string packageId, string packageVersion) + public static async Task LoadPackage(string packageId, string packageVersion, HashSet assemblyPaths) { var version = NuGetVersion.Parse(packageVersion); var nuGetFramework = NuGetFramework.ParseFolder("netcoreapp3.1"); var settings = Settings.LoadDefaultSettings(null); var sourceRepositoryProvider = new SourceRepositoryProvider(new PackageSourceProvider(settings), Repository.Provider.GetCoreV3()); - var packagesPath = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.NuGetHome), "packages"); + var packagesPath = SettingsUtility.GetGlobalPackagesFolder(settings); using (var cacheContext = new SourceCacheContext()) { @@ -49,7 +49,7 @@ await GetPackageDependencies( var resolver = new PackageResolver(); var packagesToInstall = resolver.Resolve(resolverContext, CancellationToken.None) .Select(p => availablePackages.Single(x => PackageIdentityComparer.Default.Equals(x, p))); - var packagePathResolver = new PackagePathResolver(Path.GetFullPath(packagesPath)); + var packagePathResolver = new PackagePathResolver(packagesPath, true); var packageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv3, XmlDocFileSaveMode.None, @@ -57,7 +57,6 @@ await GetPackageDependencies( NullLogger.Instance); var frameworkReducer = new FrameworkReducer(); - var assembliesToLoad = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var packageToInstall in packagesToInstall) { @@ -69,7 +68,7 @@ await GetPackageDependencies( var downloadResult = await downloadResource.GetDownloadResourceResultAsync( packageToInstall, new PackageDownloadContext(cacheContext), - SettingsUtility.GetGlobalPackagesFolder(settings), + packagesPath, NullLogger.Instance, CancellationToken.None); await PackageExtractor.ExtractPackageAsync( @@ -85,7 +84,7 @@ await PackageExtractor.ExtractPackageAsync( var libItems = packageReader.GetLibItems(); var nearest = frameworkReducer.GetNearest(nuGetFramework, libItems.Select(x => x.TargetFramework)); - assembliesToLoad.AddRange(libItems + assemblyPaths.AddRange(libItems .Where(x => x.TargetFramework.Equals(nearest)) .SelectMany(x => x.Items) .Where(x => x.EndsWith(".dll")) @@ -94,17 +93,12 @@ await PackageExtractor.ExtractPackageAsync( var frameworkItems = packageReader.GetFrameworkItems(); nearest = frameworkReducer.GetNearest(nuGetFramework, frameworkItems.Select(x => x.TargetFramework)); - assembliesToLoad.AddRange(frameworkItems + assemblyPaths.AddRange(frameworkItems .Where(x => x.TargetFramework.Equals(nearest)) .SelectMany(x => x.Items) .Where(x => x.EndsWith(".dll")) .Select(x => Path.Combine(installedPath, x))); } - - foreach (var assemblyPath in assembliesToLoad) - { - Assembly.LoadFrom(assemblyPath); - } } } diff --git a/Program.cs b/Program.cs index d737531..ce17c82 100644 --- a/Program.cs +++ b/Program.cs @@ -155,7 +155,9 @@ static bool TryGetCache(string assemblyFile, string hashFile, string configFile, return true; } - static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, string configFile, byte[] scriptHash, out Config config) + const string NuGetReferenceRegex = @"^\s*#r\s+""\s*nuget:\s*(?[\w\d.-]+)\s*\/\s*(?[\w\d.-]+)\s*""\s*$"; + + static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, string configFile, byte[] scriptHash, IEnumerable references, out Config config) { config = null; var lines = File.ReadAllLines(scriptFile); @@ -163,8 +165,12 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st var options = ScriptOptions.Default .WithEmitDebugInformation(true) .WithFilePath(scriptFile) + .AddReferences(references) ; - var compilation = CSharpScript.Create(string.Join(Environment.NewLine, lines), options, typeof(ScriptGlobals)).GetCompilation(); + + var script = string.Join(Environment.NewLine, lines); + script = Regex.Replace(script, NuGetReferenceRegex, string.Empty, RegexOptions.Multiline | RegexOptions.IgnoreCase); + var compilation = CSharpScript.Create(script, options, typeof(ScriptGlobals)).GetCompilation(); var result = compilation.Emit(assemblyFile); PrintCompilationDiagnostics(result, lines); if (!result.Success) @@ -187,11 +193,14 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st return true; } - static void LoadPackages(string scriptPath) + static IEnumerable LoadPackages(string scriptPath) { - var matches = Regex.Matches(File.ReadAllText(scriptPath), @"^//#AddPackage\s+""(?[\w.-]+),\s*(?[\w.-]+)""\s*$", RegexOptions.Multiline); + var referencePaths = new HashSet(StringComparer.OrdinalIgnoreCase); + var matches = Regex.Matches(File.ReadAllText(scriptPath), NuGetReferenceRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase); foreach (Match match in matches) - NuGet.LoadPackage(match.Groups["name"].Value, match.Groups["version"].Value).Wait(); + NuGet.LoadPackage(match.Groups["name"].Value, match.Groups["version"].Value, referencePaths).Wait(); + foreach (var path in referencePaths) + yield return Assembly.LoadFrom(path); } static void RunScript(string[] args) @@ -221,7 +230,7 @@ static void RunScript(string[] args) } } - LoadPackages(scriptPath); + var nuGetAssemblies = LoadPackages(scriptPath); var cacheFileBase = GetCacheFilenameBase(scriptPath); var assemblyFile = cacheFileBase + ".dll"; @@ -231,7 +240,7 @@ static void RunScript(string[] args) if (!TryGetCache(assemblyFile, hashFile, configFile, scriptHash, out var config)) { - if (!TryBuild(scriptPath, assemblyFile, hashFile, configFile, scriptHash, out config)) + if (!TryBuild(scriptPath, assemblyFile, hashFile, configFile, scriptHash, nuGetAssemblies, out config)) return; } diff --git a/Templates/Script.csx b/Templates/Script.csx index 481569d..eafd3ef 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -11,9 +11,9 @@ // .NET assemblies can be referenced with the '#r "AssemblyName"' directive, for example: // #r "PresentationFramework" // #r "System.Windows.Forms" -// References to NuGet packages can be added by adding a line which matches the Regex: -// ^//#AddPackage\s+"(?[\w.-]+),\s*(?[\w.-]+)"\s*$ -// e.g. //#AddPackage "System.Threading.Thread, 4.3.0" +// References to NuGet packages can be added with the syntax +// '#r "nuget: {Package}/{Version}"', for example: +// #r "nuget: System.Data.OleDb/4.7.0" using System; using System.Collections.Generic; diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index b2760e8..d93d540 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -11,9 +11,9 @@ // .NET assemblies can be referenced with the '#r "AssemblyName"' directive, for example: // #r "PresentationFramework" // #r "System.Windows.Forms" -// References to NuGet packages can be added by adding a line which matches the Regex: -// ^//#AddPackage\s+"(?[\w.-]+),\s*(?[\w.-]+)"\s*$ -// e.g. //#AddPackage "System.Threading.Thread, 4.3.0" +// References to NuGet packages can be added with the syntax +// '#r "nuget: {Package}/{Version}"', for example: +// #r "nuget: System.Data.OleDb/4.7.0" #r "PresentationFramework" From b1cbb3f1a81a90b8f351bbb29afd597a5c1f6a1b Mon Sep 17 00:00:00 2001 From: dev Date: Wed, 8 Jan 2020 11:17:58 +0100 Subject: [PATCH 04/43] Improved nuget dependency loading --- CSharpScriptRunner.csproj | 37 +++++++++++++++++++++- NuGet.cs | 65 ++++++++++++++++++++++++++------------- Program.cs | 30 +++++++++++------- Templates/Script.csx | 1 - 4 files changed, 99 insertions(+), 34 deletions(-) diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index 31526a2..afcd70c 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -2,7 +2,6 @@ Exe - netcoreapp3.1 true true @@ -22,4 +21,40 @@ + + + $(IntermediateOutputPath)BuildInfo.cs + + + +namespace CSharpScriptRunner +{ + static class BuildInfo + { + public const string RuntimeIdentifier = "$(RuntimeIdentifier)"%3B + } +} + + + + +namespace CSharpScriptRunner +{ + static class BuildInfo + { + public const string RuntimeIdentifier = "win-x64"%3B + } +} + + + + + + + + + diff --git a/NuGet.cs b/NuGet.cs index 0e1b26d..4a097cb 100644 --- a/NuGet.cs +++ b/NuGet.cs @@ -20,13 +20,15 @@ namespace CSharpScriptRunner { static class NuGet { - public static async Task LoadPackage(string packageId, string packageVersion, HashSet assemblyPaths) + public static async Task LoadPackage(string packageId, string packageVersion, HashSet buildReferences, HashSet runtimeReferences) { - var version = NuGetVersion.Parse(packageVersion); - var nuGetFramework = NuGetFramework.ParseFolder("netcoreapp3.1"); + Console.WriteLine($"Loading package '{packageId} ({packageVersion})'..."); + var version = NuGetVersion.Parse(packageVersion); + var nuGetFramework = NuGetFramework.ParseFrameworkName(AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName, DefaultFrameworkNameProvider.Instance); var settings = Settings.LoadDefaultSettings(null); var sourceRepositoryProvider = new SourceRepositoryProvider(new PackageSourceProvider(settings), Repository.Provider.GetCoreV3()); var packagesPath = SettingsUtility.GetGlobalPackagesFolder(settings); + var runtimeFramework = NuGetFramework.ParseFolder(BuildInfo.RuntimeIdentifier); using (var cacheContext = new SourceCacheContext()) { @@ -59,11 +61,11 @@ await GetPackageDependencies( var frameworkReducer = new FrameworkReducer(); foreach (var packageToInstall in packagesToInstall) - { - PackageReaderBase packageReader; + { var installedPath = packagePathResolver.GetInstalledPath(packageToInstall); if (installedPath == null) { + Console.WriteLine($"Installing package '{packageToInstall.Id} ({packageToInstall.Version})'..."); var downloadResource = await packageToInstall.Source.GetResourceAsync(CancellationToken.None); var downloadResult = await downloadResource.GetDownloadResourceResultAsync( packageToInstall, @@ -80,24 +82,34 @@ await PackageExtractor.ExtractPackageAsync( } installedPath = packagePathResolver.GetInstalledPath(packageToInstall); - packageReader = new PackageFolderReader(installedPath); - - var libItems = packageReader.GetLibItems(); - var nearest = frameworkReducer.GetNearest(nuGetFramework, libItems.Select(x => x.TargetFramework)); - assemblyPaths.AddRange(libItems - .Where(x => x.TargetFramework.Equals(nearest)) - .SelectMany(x => x.Items) - .Where(x => x.EndsWith(".dll")) - .Select(x => Path.Combine(installedPath, x))); + var packageReader = new PackageFolderReader(installedPath); - var frameworkItems = packageReader.GetFrameworkItems(); - nearest = frameworkReducer.GetNearest(nuGetFramework, frameworkItems.Select(x => x.TargetFramework)); + if (buildReferences != null) + { + var items = await packageReader.GetReferenceItemsAsync(CancellationToken.None); + var paths = GetAssemblyPaths(items, frameworkReducer, nuGetFramework, installedPath); + buildReferences.AddRange(paths); + } - assemblyPaths.AddRange(frameworkItems - .Where(x => x.TargetFramework.Equals(nearest)) - .SelectMany(x => x.Items) - .Where(x => x.EndsWith(".dll")) - .Select(x => Path.Combine(installedPath, x))); + if (runtimeReferences != null) + { + var items = await packageReader.GetItemsAsync("runtimes", CancellationToken.None); + var nearest = items.Select(x => x.TargetFramework) + .Where(x => x.Framework == runtimeFramework.Framework && (!x.HasProfile ||x.Profile == runtimeFramework.Profile)) + .OrderBy(x => x.HasProfile ? 1 : -1) + .FirstOrDefault(); + + var runtimeDir = items.FirstOrDefault(x => x.TargetFramework.Equals(nearest))?.Items.FirstOrDefault()?.Split('/').ElementAtOrDefault(1); + if (runtimeDir != null) + { + installedPath = Path.Combine(installedPath, "runtimes", runtimeDir); + packageReader = new PackageFolderReader(installedPath); + } + + items = await packageReader.GetLibItemsAsync(CancellationToken.None); + var paths = GetAssemblyPaths(items, frameworkReducer, nuGetFramework, installedPath); + runtimeReferences.AddRange(paths); + } } } } @@ -129,5 +141,16 @@ await GetPackageDependencies( } } } + + + static IEnumerable GetAssemblyPaths(IEnumerable items, FrameworkReducer frameworkReducer, NuGetFramework nuGetFramework, string installedPath) + { + var nearest = frameworkReducer.GetNearest(nuGetFramework, items.Select(x => x.TargetFramework)); + return items + .Where(x => x.TargetFramework.Equals(nearest)) + .SelectMany(x => x.Items) + .Where(x => x.EndsWith(".dll")) + .Select(x => Path.Combine(installedPath, x)); + } } } \ No newline at end of file diff --git a/Program.cs b/Program.cs index ce17c82..68dcd0b 100644 --- a/Program.cs +++ b/Program.cs @@ -16,6 +16,7 @@ using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; using System.Text.RegularExpressions; +using Microsoft.CodeAnalysis.Scripting.Hosting; namespace CSharpScriptRunner { @@ -45,8 +46,11 @@ static void Main(string[] args) } catch (Exception ex) { + if (ex is AggregateException aggregateException) + ex = aggregateException.InnerException; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ex); + Console.ResetColor(); System.Threading.Thread.Sleep(5000); } } @@ -157,7 +161,7 @@ static bool TryGetCache(string assemblyFile, string hashFile, string configFile, const string NuGetReferenceRegex = @"^\s*#r\s+""\s*nuget:\s*(?[\w\d.-]+)\s*\/\s*(?[\w\d.-]+)\s*""\s*$"; - static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, string configFile, byte[] scriptHash, IEnumerable references, out Config config) + static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, string configFile, byte[] scriptHash, IEnumerable references, out Config config) { config = null; var lines = File.ReadAllLines(scriptFile); @@ -167,9 +171,9 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st .WithFilePath(scriptFile) .AddReferences(references) ; - + var script = string.Join(Environment.NewLine, lines); - script = Regex.Replace(script, NuGetReferenceRegex, string.Empty, RegexOptions.Multiline | RegexOptions.IgnoreCase); + script = Regex.Replace(script, NuGetReferenceRegex, Environment.NewLine, RegexOptions.Multiline | RegexOptions.IgnoreCase); var compilation = CSharpScript.Create(script, options, typeof(ScriptGlobals)).GetCompilation(); var result = compilation.Emit(assemblyFile); PrintCompilationDiagnostics(result, lines); @@ -193,14 +197,18 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st return true; } - static IEnumerable LoadPackages(string scriptPath) + static IEnumerable LoadPackages(string scriptPath, out InteractiveAssemblyLoader assemblyLoader) { - var referencePaths = new HashSet(StringComparer.OrdinalIgnoreCase); + var buildReferences = new HashSet(StringComparer.OrdinalIgnoreCase); + var runtimeReferences = new HashSet(StringComparer.OrdinalIgnoreCase); var matches = Regex.Matches(File.ReadAllText(scriptPath), NuGetReferenceRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase); foreach (Match match in matches) - NuGet.LoadPackage(match.Groups["name"].Value, match.Groups["version"].Value, referencePaths).Wait(); - foreach (var path in referencePaths) - yield return Assembly.LoadFrom(path); + NuGet.LoadPackage(match.Groups["name"].Value, match.Groups["version"].Value, buildReferences, runtimeReferences).Wait(); + + assemblyLoader = new InteractiveAssemblyLoader(); + foreach (var path in runtimeReferences) + assemblyLoader.RegisterDependency(Assembly.LoadFrom(path)); + return buildReferences; } static void RunScript(string[] args) @@ -230,7 +238,7 @@ static void RunScript(string[] args) } } - var nuGetAssemblies = LoadPackages(scriptPath); + var buildReferences = LoadPackages(scriptPath, out var assemblyLoader); var cacheFileBase = GetCacheFilenameBase(scriptPath); var assemblyFile = cacheFileBase + ".dll"; @@ -240,7 +248,7 @@ static void RunScript(string[] args) if (!TryGetCache(assemblyFile, hashFile, configFile, scriptHash, out var config)) { - if (!TryBuild(scriptPath, assemblyFile, hashFile, configFile, scriptHash, nuGetAssemblies, out config)) + if (!TryBuild(scriptPath, assemblyFile, hashFile, configFile, scriptHash, buildReferences, out config)) return; } @@ -253,7 +261,7 @@ static void RunScript(string[] args) return; Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath); - var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), null } }); + var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), assemblyLoader } }); task.Wait(); } diff --git a/Templates/Script.csx b/Templates/Script.csx index eafd3ef..30f29ee 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -13,7 +13,6 @@ // #r "System.Windows.Forms" // References to NuGet packages can be added with the syntax // '#r "nuget: {Package}/{Version}"', for example: -// #r "nuget: System.Data.OleDb/4.7.0" using System; using System.Collections.Generic; From 10e8d816f0b83399f80856fd4a0dbc7a2ba558b5 Mon Sep 17 00:00:00 2001 From: dev Date: Wed, 8 Jan 2020 12:31:05 +0100 Subject: [PATCH 05/43] Missing comment in template --- Templates/Script.csx | 1 + 1 file changed, 1 insertion(+) diff --git a/Templates/Script.csx b/Templates/Script.csx index 30f29ee..eafd3ef 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -13,6 +13,7 @@ // #r "System.Windows.Forms" // References to NuGet packages can be added with the syntax // '#r "nuget: {Package}/{Version}"', for example: +// #r "nuget: System.Data.OleDb/4.7.0" using System; using System.Collections.Generic; From e450d53de4130d881861a30a27921cff160e40b9 Mon Sep 17 00:00:00 2001 From: dev Date: Wed, 8 Jan 2020 16:49:25 +0100 Subject: [PATCH 06/43] Added script debugging support --- CSharpScriptRunner.csproj | 2 ++ NuGet.cs | 20 ++++++++++---------- Program.cs | 18 +++++++++++------- 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index afcd70c..a95aafb 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -32,6 +32,7 @@ namespace CSharpScriptRunner static class BuildInfo { public const string RuntimeIdentifier = "$(RuntimeIdentifier)"%3B + public const string Configuration = "$(Configuration)"%3B } } @@ -43,6 +44,7 @@ namespace CSharpScriptRunner static class BuildInfo { public const string RuntimeIdentifier = "win-x64"%3B + public const string Configuration = "$(Configuration)"%3B } } diff --git a/NuGet.cs b/NuGet.cs index 4a097cb..cc88b27 100644 --- a/NuGet.cs +++ b/NuGet.cs @@ -23,7 +23,7 @@ static class NuGet public static async Task LoadPackage(string packageId, string packageVersion, HashSet buildReferences, HashSet runtimeReferences) { Console.WriteLine($"Loading package '{packageId} ({packageVersion})'..."); - var version = NuGetVersion.Parse(packageVersion); + var version = NuGetVersion.Parse(packageVersion); var nuGetFramework = NuGetFramework.ParseFrameworkName(AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName, DefaultFrameworkNameProvider.Instance); var settings = Settings.LoadDefaultSettings(null); var sourceRepositoryProvider = new SourceRepositoryProvider(new PackageSourceProvider(settings), Repository.Provider.GetCoreV3()); @@ -61,7 +61,7 @@ await GetPackageDependencies( var frameworkReducer = new FrameworkReducer(); foreach (var packageToInstall in packagesToInstall) - { + { var installedPath = packagePathResolver.GetInstalledPath(packageToInstall); if (installedPath == null) { @@ -80,7 +80,7 @@ await PackageExtractor.ExtractPackageAsync( packageExtractionContext, CancellationToken.None); } - + installedPath = packagePathResolver.GetInstalledPath(packageToInstall); var packageReader = new PackageFolderReader(installedPath); @@ -92,23 +92,23 @@ await PackageExtractor.ExtractPackageAsync( } if (runtimeReferences != null) - { + { var items = await packageReader.GetItemsAsync("runtimes", CancellationToken.None); var nearest = items.Select(x => x.TargetFramework) - .Where(x => x.Framework == runtimeFramework.Framework && (!x.HasProfile ||x.Profile == runtimeFramework.Profile)) + .Where(x => x.Framework == runtimeFramework.Framework && (!x.HasProfile || x.Profile == runtimeFramework.Profile)) .OrderBy(x => x.HasProfile ? 1 : -1) .FirstOrDefault(); - + var runtimeDir = items.FirstOrDefault(x => x.TargetFramework.Equals(nearest))?.Items.FirstOrDefault()?.Split('/').ElementAtOrDefault(1); if (runtimeDir != null) { installedPath = Path.Combine(installedPath, "runtimes", runtimeDir); packageReader = new PackageFolderReader(installedPath); } - + items = await packageReader.GetLibItemsAsync(CancellationToken.None); var paths = GetAssemblyPaths(items, frameworkReducer, nuGetFramework, installedPath); - runtimeReferences.AddRange(paths); + runtimeReferences.AddRange(paths); } } } @@ -141,8 +141,8 @@ await GetPackageDependencies( } } } - - + + static IEnumerable GetAssemblyPaths(IEnumerable items, FrameworkReducer frameworkReducer, NuGetFramework nuGetFramework, string installedPath) { var nearest = frameworkReducer.GetNearest(nuGetFramework, items.Select(x => x.TargetFramework)); diff --git a/Program.cs b/Program.cs index 68dcd0b..ffe8afc 100644 --- a/Program.cs +++ b/Program.cs @@ -169,18 +169,22 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st var options = ScriptOptions.Default .WithEmitDebugInformation(true) .WithFilePath(scriptFile) + .WithFileEncoding(Encoding.UTF8) .AddReferences(references) ; - + var script = string.Join(Environment.NewLine, lines); script = Regex.Replace(script, NuGetReferenceRegex, Environment.NewLine, RegexOptions.Multiline | RegexOptions.IgnoreCase); var compilation = CSharpScript.Create(script, options, typeof(ScriptGlobals)).GetCompilation(); - var result = compilation.Emit(assemblyFile); - PrintCompilationDiagnostics(result, lines); - if (!result.Success) + using (var stream = File.OpenWrite(assemblyFile)) { - System.Threading.Thread.Sleep(5000); - return false; + var result = compilation.Emit(stream, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded)); + PrintCompilationDiagnostics(result, lines); + if (!result.Success) + { + System.Threading.Thread.Sleep(5000); + return false; + } } File.WriteAllBytes(hashFile, scriptHash); @@ -259,7 +263,7 @@ static void RunScript(string[] args) var entryPoint = type.GetMethod(config.Method, BindingFlags.Static | BindingFlags.Public); if (entryPoint == null) return; - + Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath); var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), assemblyLoader } }); task.Wait(); From 64afeefeb518a0eaad01adb1e736ffa86e43c18b Mon Sep 17 00:00:00 2001 From: dev Date: Wed, 8 Jan 2020 17:02:17 +0100 Subject: [PATCH 07/43] Added alias csx for CSharpScriptRunner --- Program.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Program.cs b/Program.cs index ffe8afc..23b7a3c 100644 --- a/Program.cs +++ b/Program.cs @@ -29,6 +29,8 @@ public sealed class ScriptGlobals static class Program { + const string CmdAlias = "csx"; + [STAThread] static void Main(string[] args) { @@ -79,6 +81,8 @@ static void Install() Directory.CreateDirectory(Path.GetDirectoryName(dst)); Console.WriteLine($"Copying {dst} ..."); File.Copy(file, dst, true); + if (Path.GetFileName(file) == filename) + File.Copy(file, Path.Combine(Path.GetDirectoryName(dst), CmdAlias + Path.GetExtension(filename)), true); }))).Wait(); } From e936c7fe873bc3289519b7b6f9dbecb4808a6327 Mon Sep 17 00:00:00 2001 From: dev Date: Thu, 9 Jan 2020 10:23:31 +0100 Subject: [PATCH 08/43] [+] Updates.CheckFornewRelease --- .github/workflows/main.yml | 8 +++--- CSharpScriptRunner.csproj | 3 +++ Program.cs | 2 ++ Updates.cs | 50 ++++++++++++++++++++++++++++++++++++++ publish.ps1 | 4 +-- 5 files changed, 61 insertions(+), 6 deletions(-) create mode 100644 Updates.cs diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index e8e5a6e..8943ee6 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -19,7 +19,7 @@ jobs: publish: runs-on: windows-latest - if: contains(github.ref, 'tags/v') # works only version tagged + if: startsWith(github.ref, 'refs/tags/v') # works only version tagged needs: [build] steps: @@ -40,8 +40,8 @@ jobs: prerelease: false - name: Build run: | - dotnet publish -c Release -r win-x86 -o ./publish/x86 - dotnet publish -c Release -r win-x64 -o ./publish/x64 + dotnet publish -c Release -r win-x86 -o ./publish/x86 -p:ReleaseTag=${{ github.ref:10 }} + dotnet publish -c Release -r win-x64 -o ./publish/x64 -p:ReleaseTag=${{ github.ref:10 }} Compress-Archive -Path ./publish/* -DestinationPath ./publish/win.zip -CompressionLevel Optimal - name: Upload Release Asset id: upload-release-asset @@ -51,5 +51,5 @@ jobs: with: upload_url: ${{ steps.create_release.outputs.upload_url }} asset_path: ./publish/win.zip - asset_name: ${{ github.ref }}-win.zip + asset_name: CSharpScriptRunner-${{ github.ref:10 }}-win.zip asset_content_type: application/zip diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index a95aafb..a31db84 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -5,6 +5,7 @@ netcoreapp3.1 true true + dev @@ -33,6 +34,7 @@ namespace CSharpScriptRunner { public const string RuntimeIdentifier = "$(RuntimeIdentifier)"%3B public const string Configuration = "$(Configuration)"%3B + public const string ReleaseTag = "$(ReleaseTag)"%3B } } @@ -45,6 +47,7 @@ namespace CSharpScriptRunner { public const string RuntimeIdentifier = "win-x64"%3B public const string Configuration = "$(Configuration)"%3B + public const string ReleaseTag = "$(ReleaseTag)"%3B } } diff --git a/Program.cs b/Program.cs index 23b7a3c..5330c7d 100644 --- a/Program.cs +++ b/Program.cs @@ -34,6 +34,8 @@ static class Program [STAThread] static void Main(string[] args) { + Console.WriteLine($"{nameof(CSharpScriptRunner)}, {BuildInfo.ReleaseTag}"); + if (args == null || args.Length == 0) return; diff --git a/Updates.cs b/Updates.cs new file mode 100644 index 0000000..9912e21 --- /dev/null +++ b/Updates.cs @@ -0,0 +1,50 @@ +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Collections.Generic; +using System; + +namespace CSharpScriptRunner +{ + sealed class ReleaseInfo + { + [JsonPropertyName("tag_name")] + public string Version { get; set; } + + [JsonPropertyName("html_url")] + public string Url { get; set; } + } + + static class Updates + { + public static async Task CheckForNewRelease() + { + const string RequestUri = "https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest"; + + if (!BuildInfo.ReleaseTag.StartsWith('v') || !Version.TryParse(BuildInfo.ReleaseTag, out var version)) + return default; + + using (var httpClient = new HttpClient()) + { + httpClient.DefaultRequestHeaders.Accept.Clear(); + httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + httpClient.DefaultRequestHeaders.Add("User-Agent", "CSharpScriptRunner"); + HttpResponseMessage response; + try { response = await httpClient.GetAsync(RequestUri); } + catch { return default; } + if (!response.IsSuccessStatusCode) + return default; + + var release = JsonSerializer.Deserialize(await response.Content.ReadAsByteArrayAsync()); + if (string.IsNullOrEmpty(release.Version) || string.IsNullOrEmpty(release.Url) || !release.Version.StartsWith('v') || !Version.TryParse(release.Version.Substring(1), out var releaseVersion)) + return default; + + if (version < releaseVersion) + return release; + } + return default; + } + } +} \ No newline at end of file diff --git a/publish.ps1 b/publish.ps1 index e5f85b3..a760e08 100644 --- a/publish.ps1 +++ b/publish.ps1 @@ -1,2 +1,2 @@ -dotnet publish -c Release -r win-x86 -o publish\x86 -dotnet publish -c Release -r win-x64 -o publish\x64 \ No newline at end of file +dotnet publish -c Release -r win-x86 -o publish\x86 -p:ReleaseTag=dev +dotnet publish -c Release -r win-x64 -o publish\x64 -p:ReleaseTag=dev \ No newline at end of file From 32e295e61c2e9a177ce581829496efb7b6efedbf Mon Sep 17 00:00:00 2001 From: dev Date: Thu, 9 Jan 2020 16:16:30 +0100 Subject: [PATCH 09/43] Fix --- .github/workflows/main.yml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 8943ee6..0482da7 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -40,8 +40,11 @@ jobs: prerelease: false - name: Build run: | - dotnet publish -c Release -r win-x86 -o ./publish/x86 -p:ReleaseTag=${{ github.ref:10 }} - dotnet publish -c Release -r win-x64 -o ./publish/x64 -p:ReleaseTag=${{ github.ref:10 }} + $version = "${{ github.ref }}" + $version = $version.Substring(10) + echo "::set-env name=RELEASE_TAG::$version" + dotnet publish -c Release -r win-x86 -o ./publish/x86 -p:ReleaseTag=$version + dotnet publish -c Release -r win-x64 -o ./publish/x64 -p:ReleaseTag=$version Compress-Archive -Path ./publish/* -DestinationPath ./publish/win.zip -CompressionLevel Optimal - name: Upload Release Asset id: upload-release-asset @@ -51,5 +54,5 @@ jobs: with: upload_url: ${{ steps.create_release.outputs.upload_url }} asset_path: ./publish/win.zip - asset_name: CSharpScriptRunner-${{ github.ref:10 }}-win.zip + asset_name: CSharpScriptRunner-${{ RELEASE_TAG }}-win.zip asset_content_type: application/zip From c2ac33bc95141ac0c9904ac15dfc608535584780 Mon Sep 17 00:00:00 2001 From: dev Date: Thu, 9 Jan 2020 16:22:51 +0100 Subject: [PATCH 10/43] Fix --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 0482da7..241f1df 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -54,5 +54,5 @@ jobs: with: upload_url: ${{ steps.create_release.outputs.upload_url }} asset_path: ./publish/win.zip - asset_name: CSharpScriptRunner-${{ RELEASE_TAG }}-win.zip + asset_name: CSharpScriptRunner-${{ env.RELEASE_TAG }}-win.zip asset_content_type: application/zip From 6aabf553cbced234160c7835cbb12ce8678e3d53 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 10 Jan 2020 08:20:22 +0100 Subject: [PATCH 11/43] Check for new release --- Program.cs | 7 ++++++- Updates.cs | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/Program.cs b/Program.cs index 5330c7d..8459ee3 100644 --- a/Program.cs +++ b/Program.cs @@ -171,7 +171,7 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st { config = null; var lines = File.ReadAllLines(scriptFile); - Console.WriteLine($"Compiling script {scriptFile}..."); + Console.WriteLine($"Compiling script '{scriptFile}'..."); var options = ScriptOptions.Default .WithEmitDebugInformation(true) .WithFilePath(scriptFile) @@ -258,6 +258,11 @@ static void RunScript(string[] args) if (!TryGetCache(assemblyFile, hashFile, configFile, scriptHash, out var config)) { + // Check for new release only when compiling + var newRelease = Updates.CheckForNewRelease().Result; + if (newRelease != default) + Console.WriteLine($"A new release of {nameof(CSharpScriptRunner)} ({newRelease.Version}) is available at {newRelease.Url}"); + if (!TryBuild(scriptPath, assemblyFile, hashFile, configFile, scriptHash, buildReferences, out config)) return; } diff --git a/Updates.cs b/Updates.cs index 9912e21..29a3e2d 100644 --- a/Updates.cs +++ b/Updates.cs @@ -23,7 +23,7 @@ public static async Task CheckForNewRelease() { const string RequestUri = "https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest"; - if (!BuildInfo.ReleaseTag.StartsWith('v') || !Version.TryParse(BuildInfo.ReleaseTag, out var version)) + if (!BuildInfo.ReleaseTag.StartsWith('v') || !Version.TryParse(BuildInfo.ReleaseTag.Substring(1), out var version)) return default; using (var httpClient = new HttpClient()) From 2b259f1832c783ee78c17174ad2dd5350119419a Mon Sep 17 00:00:00 2001 From: dev Date: Tue, 14 Jan 2020 12:28:11 +0100 Subject: [PATCH 12/43] Print help --- .github/workflows/main.yml | 16 +++---- CSharpScriptRunner.csproj | 1 + Program.cs | 93 +++++++++++++++++++++++++++----------- 3 files changed, 75 insertions(+), 35 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 241f1df..0b9a016 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -28,6 +28,14 @@ jobs: uses: actions/setup-dotnet@v1.0.0 with: version: 3.1.100 + - name: Build + run: | + $version = "${{ github.ref }}" + $version = $version.Substring(10) + echo "::set-env name=RELEASE_TAG::$version" + dotnet publish -c Release -r win-x86 -o ./publish/x86 -p:ReleaseTag=$version + dotnet publish -c Release -r win-x64 -o ./publish/x64 -p:ReleaseTag=$version + Compress-Archive -Path ./publish/* -DestinationPath ./publish/win.zip -CompressionLevel Optimal - name: Create Release id: create_release uses: actions/create-release@v1.0.0 @@ -38,14 +46,6 @@ jobs: release_name: Release ${{ github.ref }} draft: false prerelease: false - - name: Build - run: | - $version = "${{ github.ref }}" - $version = $version.Substring(10) - echo "::set-env name=RELEASE_TAG::$version" - dotnet publish -c Release -r win-x86 -o ./publish/x86 -p:ReleaseTag=$version - dotnet publish -c Release -r win-x64 -o ./publish/x64 -p:ReleaseTag=$version - Compress-Archive -Path ./publish/* -DestinationPath ./publish/win.zip -CompressionLevel Optimal - name: Upload Release Asset id: upload-release-asset uses: actions/upload-release-asset@v1.0.1 diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index a31db84..a1863a9 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -1,6 +1,7 @@ + C# Script Runner Exe netcoreapp3.1 true diff --git a/Program.cs b/Program.cs index 8459ee3..723b19c 100644 --- a/Program.cs +++ b/Program.cs @@ -17,6 +17,7 @@ using Microsoft.CodeAnalysis.Scripting; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Scripting.Hosting; +using Microsoft.CodeAnalysis.CSharp; namespace CSharpScriptRunner { @@ -30,6 +31,14 @@ public sealed class ScriptGlobals static class Program { const string CmdAlias = "csx"; + static readonly string CachePath = Path.Combine(Path.GetTempPath(), nameof(CSharpScriptRunner)); + + static class Verbs + { + public const string Install = "install"; + public const string New = "new"; + public const string ClearCache = "clear-cache"; + } [STAThread] static void Main(string[] args) @@ -37,28 +46,45 @@ static void Main(string[] args) Console.WriteLine($"{nameof(CSharpScriptRunner)}, {BuildInfo.ReleaseTag}"); if (args == null || args.Length == 0) + { + PrintHelp(); return; + } try { - if (args[0] == "install") - Install(); - else if (args[0] == "new") - CreateNew(args.Length > 1 ? args[1] : null); - else - RunScript(args); + switch (args[0].ToLowerInvariant()) + { + case Verbs.Install: Install(); break; + case Verbs.New: CreateNew(args.Length > 1 ? args[1] : null); break; + case Verbs.ClearCache: ClearCache(); break; + default: RunScript(args); break; + } } catch (Exception ex) { if (ex is AggregateException aggregateException) ex = aggregateException.InnerException; - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine(ex); - Console.ResetColor(); + WriteLine(ex.ToString(), ConsoleColor.Red); System.Threading.Thread.Sleep(5000); } } + static void PrintHelp() + { + var exe = nameof(CSharpScriptRunner); + Console.WriteLine($"Alias: {CmdAlias}"); + Console.WriteLine($"{exe} ScriptFilePath [args]"); + Console.WriteLine($" Executes the specified script."); + Console.WriteLine($"{exe} {Verbs.Install}"); + Console.WriteLine($" Installs {exe} for the current user."); + Console.WriteLine($"{exe} {Verbs.New} [template]"); + Console.WriteLine($" If a template name is provided, a new script file [template].csx is created."); + Console.WriteLine($" If the template name is omitted, the available templates are listed."); + Console.WriteLine($"{exe} {Verbs.ClearCache}"); + Console.WriteLine($" Cleares the cache of previously compiled scripts."); + } + static void Install() { var oldPath = Process.GetCurrentProcess().MainModule.FileName; @@ -115,9 +141,7 @@ static void Install() regKeyCommand.SetValue(string.Empty, $"\"{newPath}\" \"%1\""); } - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("Installation was successful."); - Console.ResetColor(); + WriteLine("Installation was successful.", ConsoleColor.Green); System.Threading.Thread.Sleep(5000); } @@ -129,9 +153,8 @@ static string GetCacheFilenameBase(string filename) var result = new StringBuilder(bytes.Length * 2); foreach (var b in bytes) result.Append(b.ToString("X2")); - var dir = Path.Combine(Path.GetTempPath(), nameof(CSharpScriptRunner)); - Directory.CreateDirectory(dir); - return Path.Combine(dir, result.ToString()); + Directory.CreateDirectory(CachePath); + return Path.Combine(CachePath, result.ToString()); } } @@ -182,6 +205,7 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st var script = string.Join(Environment.NewLine, lines); script = Regex.Replace(script, NuGetReferenceRegex, Environment.NewLine, RegexOptions.Multiline | RegexOptions.IgnoreCase); var compilation = CSharpScript.Create(script, options, typeof(ScriptGlobals)).GetCompilation(); + //compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.ConsoleApplication)); using (var stream = File.OpenWrite(assemblyFile)) { var result = compilation.Emit(stream, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded)); @@ -242,9 +266,7 @@ static void RunScript(string[] args) return; } - Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine($"Warning: Runtime '{runtimeExt}' was not found. Proceeding anyway..."); - Console.ResetColor(); + WriteLine($"Warning: Runtime '{runtimeExt}' was not found. Proceeding anyway...", ConsoleColor.Yellow); } } @@ -317,6 +339,7 @@ static void PrintCompilationDiagnostics(EmitResult result, string[] lines) static void CreateNew(string template) { var templates = typeof(Program).Assembly.GetManifestResourceNames() + .Where(x => string.Equals(Path.GetExtension(x), ".csx", StringComparison.OrdinalIgnoreCase)) .ToDictionary(x => Path.GetExtension(Path.GetFileNameWithoutExtension(x)).Substring(1), StringComparer.OrdinalIgnoreCase); if (template == null) @@ -324,23 +347,19 @@ static void CreateNew(string template) Console.Write("Available templates: "); Console.WriteLine(string.Join(", ", templates.Keys)); Console.Write("Enter the name of the template you wish to create: "); - template = Console.ReadLine(); + template = Console.ReadLine().Trim(); } if (!templates.TryGetValue(template, out var resName)) { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"The template '{template}' does not exists."); - Console.ResetColor(); + WriteLine($"The template '{template}' does not exists.", ConsoleColor.Red); return; } var filename = template + ".csx"; if (File.Exists(filename)) { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"The file '{filename} already exists."); - Console.ResetColor(); + WriteLine($"The file '{filename} already exists.", ConsoleColor.Red); return; } @@ -350,8 +369,28 @@ static void CreateNew(string template) res.CopyTo(file); } - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine($"The file '{filename}' was created."); + WriteLine($"The file '{filename}' was created.", ConsoleColor.Green); + } + + static void ClearCache() + { + if (!Directory.Exists(CachePath)) + return; + + Task.WhenAll(Directory.EnumerateFiles(CachePath).Select(path => Task.Run(() => + { + try { File.Delete(path); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + }))).Wait(); + WriteLine("Cache cleared", ConsoleColor.Green); + } + + static void WriteLine(string line, ConsoleColor color = (ConsoleColor)(-1)) + { + if ((int)color > -1) + Console.ForegroundColor = color; + Console.WriteLine(line); Console.ResetColor(); } } From b5b3798d1513ba737dab28304c7a20f3e6a3a618 Mon Sep 17 00:00:00 2001 From: dev Date: Thu, 16 Jan 2020 08:05:33 +0100 Subject: [PATCH 13/43] Bugfixes --- .github/workflows/main.yml | 22 +++++++++++++++++----- .gitignore | 5 +++-- Program.cs | 4 ++++ Templates/Script.csx | 2 +- Templates/ScriptUI.csx | 2 +- publish.ps1 | 5 +++-- publish/any/README | 1 + publish/{ => win}/install.bat | 0 8 files changed, 30 insertions(+), 11 deletions(-) create mode 100644 publish/any/README rename publish/{ => win}/install.bat (100%) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 0b9a016..202730a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -33,9 +33,11 @@ jobs: $version = "${{ github.ref }}" $version = $version.Substring(10) echo "::set-env name=RELEASE_TAG::$version" - dotnet publish -c Release -r win-x86 -o ./publish/x86 -p:ReleaseTag=$version - dotnet publish -c Release -r win-x64 -o ./publish/x64 -p:ReleaseTag=$version - Compress-Archive -Path ./publish/* -DestinationPath ./publish/win.zip -CompressionLevel Optimal + dotnet publish -c Release -r win-x86 -o ./publish/win/x86 -p:ReleaseTag=$version + dotnet publish -c Release -r win-x64 -o ./publish/win/x64 -p:ReleaseTag=$version + Compress-Archive -Path ./publish/win -DestinationPath ./publish/win.zip -CompressionLevel Optimal + dotnet publish -c Release -o ./publish/any -p:ReleaseTag=$version + Compress-Archive -Path ./publish/any -DestinationPath ./publish/any.zip -CompressionLevel Optimal - name: Create Release id: create_release uses: actions/create-release@v1.0.0 @@ -46,8 +48,8 @@ jobs: release_name: Release ${{ github.ref }} draft: false prerelease: false - - name: Upload Release Asset - id: upload-release-asset + - name: Upload Release Asset (win) + id: upload-release-asset-win uses: actions/upload-release-asset@v1.0.1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -56,3 +58,13 @@ jobs: asset_path: ./publish/win.zip asset_name: CSharpScriptRunner-${{ env.RELEASE_TAG }}-win.zip asset_content_type: application/zip + - name: Upload Release Asset (any) + id: upload-release-asset-any + uses: actions/upload-release-asset@v1.0.1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./publish/any.zip + asset_name: CSharpScriptRunner-${{ env.RELEASE_TAG }}-any.zip + asset_content_type: application/zip diff --git a/.gitignore b/.gitignore index 551e3d1..77e3653 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ bin obj -publish/x64 -publish/x86 +publish/win/x64 +publish/win/x86 +publish/any/any .vscode diff --git a/Program.cs b/Program.cs index 723b19c..eb5749a 100644 --- a/Program.cs +++ b/Program.cs @@ -72,6 +72,10 @@ static void Main(string[] args) static void PrintHelp() { + var newRelease = Updates.CheckForNewRelease().Result; + if (newRelease != default) + Console.WriteLine($"A new release of {nameof(CSharpScriptRunner)} ({newRelease.Version}) is available at {newRelease.Url}"); + var exe = nameof(CSharpScriptRunner); Console.WriteLine($"Alias: {CmdAlias}"); Console.WriteLine($"{exe} ScriptFilePath [args]"); diff --git a/Templates/Script.csx b/Templates/Script.csx index eafd3ef..db1a8c6 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -79,7 +79,7 @@ public static class Script public static IDictionary ParseArguments(IEnumerable args) { - var arguments = new Dictionary(); + var arguments = new Dictionary(StringComparer.OrdinalIgnoreCase); string key = null; foreach (var value in args) { diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index d93d540..405eedd 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -104,7 +104,7 @@ public static class Script public static IDictionary ParseArguments(IEnumerable args) { - var arguments = new Dictionary(); + var arguments = new Dictionary(StringComparer.OrdinalIgnoreCase); string key = null; foreach (var value in args) { diff --git a/publish.ps1 b/publish.ps1 index a760e08..1e18283 100644 --- a/publish.ps1 +++ b/publish.ps1 @@ -1,2 +1,3 @@ -dotnet publish -c Release -r win-x86 -o publish\x86 -p:ReleaseTag=dev -dotnet publish -c Release -r win-x64 -o publish\x64 -p:ReleaseTag=dev \ No newline at end of file +dotnet publish -c Release -r win-x86 -o publish/win/x86 -p:ReleaseTag=dev +dotnet publish -c Release -r win-x64 -o publish/win/x64 -p:ReleaseTag=dev +dotnet publish -c Release -o publish/any/any -p:ReleaseTag=dev \ No newline at end of file diff --git a/publish/any/README b/publish/any/README new file mode 100644 index 0000000..f5f5ef4 --- /dev/null +++ b/publish/any/README @@ -0,0 +1 @@ +Requires .NET Core 3.1 (or later) Runtime: https://docs.microsoft.com/en-us/dotnet/core/install/runtime \ No newline at end of file diff --git a/publish/install.bat b/publish/win/install.bat similarity index 100% rename from publish/install.bat rename to publish/win/install.bat From a291fdfb3bbe78529fbb8cfe799f0896cc80c33e Mon Sep 17 00:00:00 2001 From: dev Date: Sat, 18 Jan 2020 14:43:15 +0100 Subject: [PATCH 14/43] Added init-vscode argument (for debugging) --- CSharpScriptRunner.csproj | 2 +- Program.cs | 45 +++++++++++++++++++++++++++++++++++- Templates/vscode/launch.json | 27 ++++++++++++++++++++++ 3 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 Templates/vscode/launch.json diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index a1863a9..9acb111 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -10,7 +10,7 @@ - + diff --git a/Program.cs b/Program.cs index eb5749a..f8049d0 100644 --- a/Program.cs +++ b/Program.cs @@ -38,6 +38,7 @@ static class Verbs public const string Install = "install"; public const string New = "new"; public const string ClearCache = "clear-cache"; + public const string InitVSCode = "init-vscode"; } [STAThread] @@ -57,7 +58,8 @@ static void Main(string[] args) { case Verbs.Install: Install(); break; case Verbs.New: CreateNew(args.Length > 1 ? args[1] : null); break; - case Verbs.ClearCache: ClearCache(); break; + case Verbs.ClearCache: ClearCache(); break; + case Verbs.InitVSCode: InitVSCode(); break; default: RunScript(args); break; } } @@ -251,6 +253,13 @@ static IEnumerable LoadPackages(string scriptPath, out InteractiveAssemb static void RunScript(string[] args) { + if (!File.Exists(args[0])) + { + WriteLine($"Script file '{args[0]}' does not exist.", ConsoleColor.Red); + System.Threading.Thread.Sleep(5000); + return; + } + var scriptPath = Path.GetFullPath(args[0]); var runtimeExt = Path.GetExtension(Path.GetFileNameWithoutExtension(scriptPath)); if (!string.IsNullOrEmpty(runtimeExt)) @@ -390,6 +399,40 @@ static void ClearCache() WriteLine("Cache cleared", ConsoleColor.Green); } + static void InitVSCode() + { + const string VSCodeDir = ".vscode"; + const string Filter = ".Templates.vscode."; + + var templates = typeof(Program).Assembly.GetManifestResourceNames() + .Select(x => (i: x.IndexOf(Filter), s: x)) + .Where(x => x.i > -1) + .Select(x => (name: x.s, File: Path.Combine(VSCodeDir, x.s.Substring(x.i + Filter.Length)))); + + var dir = new DirectoryInfo(VSCodeDir); + if (!dir.Exists) + { + dir.Create(); + // dir.Attributes |= FileAttributes.Hidden; + } + + foreach (var template in templates) + { + if (File.Exists(template.File)) + { + WriteLine($"File '{template.File}' already exists.", ConsoleColor.Yellow); + continue; + } + + using (var stream = typeof(Program).Assembly.GetManifestResourceStream(template.name)) + using (var file = File.OpenWrite(template.File)) + { + WriteLine($"Creating file '{template.File}'...", ConsoleColor.Green); + stream.CopyTo(file); + } + } + } + static void WriteLine(string line, ConsoleColor color = (ConsoleColor)(-1)) { if ((int)color > -1) diff --git a/Templates/vscode/launch.json b/Templates/vscode/launch.json new file mode 100644 index 0000000..5c1e50f --- /dev/null +++ b/Templates/vscode/launch.json @@ -0,0 +1,27 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + + { + "name": ".NET Core Launch (console)", + "type": "coreclr", + "request": "launch", + "program": "CSharpScriptRunner", + "args": [ "${file}" ], + "cwd": "${workspaceFolder}", + "console": "internalConsole", + "stopAtEntry": false, + "requireExactSource": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach", + "processId": "${command:pickProcess}", + "requireExactSource": false + } + ] +} \ No newline at end of file From deb88651d7eca1a9d6cb08c61038599a3126c8f9 Mon Sep 17 00:00:00 2001 From: dev Date: Thu, 23 Jan 2020 08:59:40 +0100 Subject: [PATCH 15/43] Fixed problem with debugging (line-mismatch) when referencing nuget packages --- Program.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Program.cs b/Program.cs index f8049d0..d08b76c 100644 --- a/Program.cs +++ b/Program.cs @@ -87,6 +87,8 @@ static void PrintHelp() Console.WriteLine($"{exe} {Verbs.New} [template]"); Console.WriteLine($" If a template name is provided, a new script file [template].csx is created."); Console.WriteLine($" If the template name is omitted, the available templates are listed."); + Console.WriteLine($"{exe} {Verbs.InitVSCode}"); + Console.WriteLine($" Initializes VS Code debugging support (creates .vscode directory)"); Console.WriteLine($"{exe} {Verbs.ClearCache}"); Console.WriteLine($" Cleares the cache of previously compiled scripts."); } @@ -209,7 +211,7 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st ; var script = string.Join(Environment.NewLine, lines); - script = Regex.Replace(script, NuGetReferenceRegex, Environment.NewLine, RegexOptions.Multiline | RegexOptions.IgnoreCase); + script = Regex.Replace(script, NuGetReferenceRegex, match => new string(match.Value.Select(x => (x == '\r' || x == '\n') ? x : ' ').ToArray()), RegexOptions.Multiline | RegexOptions.IgnoreCase); var compilation = CSharpScript.Create(script, options, typeof(ScriptGlobals)).GetCompilation(); //compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.ConsoleApplication)); using (var stream = File.OpenWrite(assemblyFile)) @@ -413,7 +415,7 @@ static void InitVSCode() if (!dir.Exists) { dir.Create(); - // dir.Attributes |= FileAttributes.Hidden; + //dir.Attributes |= FileAttributes.Hidden; } foreach (var template in templates) From f9933861d05beacf738f2f80f93b114c503788cd Mon Sep 17 00:00:00 2001 From: dev Date: Tue, 28 Jan 2020 13:06:11 +0100 Subject: [PATCH 16/43] Add CSharpScriptRunnerRuntimesDir env var during installation --- Program.cs | 3 ++- Templates/Script.csx | 2 ++ Templates/ScriptUI.csx | 2 ++ Templates/vscode/launch.json | 3 ++- 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/Program.cs b/Program.cs index d08b76c..838ab44 100644 --- a/Program.cs +++ b/Program.cs @@ -127,6 +127,7 @@ static void Install() .Where(x => !x.Contains(nameof(CSharpScriptRunner))) .Append(Path.GetDirectoryName(newPath)); Environment.SetEnvironmentVariable("Path", string.Join(';', envPath), EnvironmentVariableTarget.User); + Environment.SetEnvironmentVariable(nameof(CSharpScriptRunner)+"RuntimesDir", Path.GetDirectoryName(Path.GetDirectoryName(newPath)), EnvironmentVariableTarget.User); var filetype = ".csx"; @@ -211,7 +212,7 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st ; var script = string.Join(Environment.NewLine, lines); - script = Regex.Replace(script, NuGetReferenceRegex, match => new string(match.Value.Select(x => (x == '\r' || x == '\n') ? x : ' ').ToArray()), RegexOptions.Multiline | RegexOptions.IgnoreCase); + script = Regex.Replace(script, NuGetReferenceRegex, match => new string(match.Value.Select(x => char.IsWhiteSpace(x) ? x : ' ').ToArray()), RegexOptions.Multiline | RegexOptions.IgnoreCase); var compilation = CSharpScript.Create(script, options, typeof(ScriptGlobals)).GetCompilation(); //compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.ConsoleApplication)); using (var stream = File.OpenWrite(assemblyFile)) diff --git a/Templates/Script.csx b/Templates/Script.csx index db1a8c6..9339ed6 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -28,6 +28,8 @@ foreach (var arg in Script.ParseArguments(Args)) Script.WriteLine("Press Enter to exit"); Console.ReadLine(); +return; // End of script + #region Utilities public static class Script diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index 405eedd..ec7ed6b 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -53,6 +53,8 @@ var window = (Window)XamlReader.Parse(@" window.DataContext = new Command(() => MessageBox.Show("Hello World!")); window.ShowDialog(); +return; // End of script + #region Utilities public static class Script diff --git a/Templates/vscode/launch.json b/Templates/vscode/launch.json index 5c1e50f..81d1625 100644 --- a/Templates/vscode/launch.json +++ b/Templates/vscode/launch.json @@ -9,7 +9,8 @@ "name": ".NET Core Launch (console)", "type": "coreclr", "request": "launch", - "program": "CSharpScriptRunner", + "program": "CSharpScriptRunner", + //"program": "${env:CSharpScriptRunnerRuntimesDir}/x64/CSharpScriptRunner", "args": [ "${file}" ], "cwd": "${workspaceFolder}", "console": "internalConsole", From ba00c4265411ce456b1f6ed805f35cf2354361cf Mon Sep 17 00:00:00 2001 From: dev Date: Wed, 5 Aug 2020 07:02:03 +0200 Subject: [PATCH 17/43] Fix --- CSharpScriptRunner.csproj | 12 +++--- Program.cs | 91 +++++++++++++++++++++++++-------------- publish/win/install.bat | 2 +- 3 files changed, 66 insertions(+), 39 deletions(-) diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index 9acb111..6e10092 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -14,13 +14,13 @@ - + - - - - - + + + + + diff --git a/Program.cs b/Program.cs index 838ab44..efbef82 100644 --- a/Program.cs +++ b/Program.cs @@ -56,7 +56,7 @@ static void Main(string[] args) { switch (args[0].ToLowerInvariant()) { - case Verbs.Install: Install(); break; + case Verbs.Install: Install(args.Length > 1 ? string.Equals(args[1], "inplace", StringComparison.OrdinalIgnoreCase) : false); break; case Verbs.New: CreateNew(args.Length > 1 ? args[1] : null); break; case Verbs.ClearCache: ClearCache(); break; case Verbs.InitVSCode: InitVSCode(); break; @@ -80,8 +80,9 @@ static void PrintHelp() var exe = nameof(CSharpScriptRunner); Console.WriteLine($"Alias: {CmdAlias}"); - Console.WriteLine($"{exe} ScriptFilePath [args]"); + Console.WriteLine($"{exe} [-r] ScriptFilePath [args]"); Console.WriteLine($" Executes the specified script."); + Console.WriteLine($" : Runtime, e.g. x86/x64"); Console.WriteLine($"{exe} {Verbs.Install}"); Console.WriteLine($" Installs {exe} for the current user."); Console.WriteLine($"{exe} {Verbs.New} [template]"); @@ -93,41 +94,50 @@ static void PrintHelp() Console.WriteLine($" Cleares the cache of previously compiled scripts."); } - static void Install() + static void Install(bool installInPlace) { var oldPath = Process.GetCurrentProcess().MainModule.FileName; + var newPath = oldPath; var filename = Path.GetFileName(oldPath); var oldDir = Path.GetDirectoryName(oldPath); var runtimeDir = Path.GetFileName(oldDir); oldDir = Path.GetDirectoryName(oldDir); - var newDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner)); - if (Directory.Exists(newDir)) - Directory.Delete(newDir, true); - Directory.CreateDirectory(newDir); - var newPath = Path.Combine(newDir, runtimeDir, filename); - - foreach (var dir in Directory.EnumerateDirectories(oldDir)) + if (installInPlace) { - if (!File.Exists(Path.Combine(dir, filename))) - continue; + foreach (var file in Directory.EnumerateFiles(oldDir, filename, SearchOption.AllDirectories)) + File.Copy(file, Path.Combine(Path.GetDirectoryName(file), CmdAlias + Path.GetExtension(filename)), true); + } + else + { + var newDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner)); + if (Directory.Exists(newDir)) + Directory.Delete(newDir, true); + Directory.CreateDirectory(newDir); + newPath = Path.Combine(newDir, runtimeDir, filename); - Task.WhenAll(Directory.EnumerateFiles(dir, "*", new EnumerationOptions { RecurseSubdirectories = true }).Select(file => Task.Run(() => + foreach (var dir in Directory.EnumerateDirectories(oldDir)) { - var dst = Path.Combine(newDir, file.Substring(oldDir.Length + 1)); - Directory.CreateDirectory(Path.GetDirectoryName(dst)); - Console.WriteLine($"Copying {dst} ..."); - File.Copy(file, dst, true); - if (Path.GetFileName(file) == filename) - File.Copy(file, Path.Combine(Path.GetDirectoryName(dst), CmdAlias + Path.GetExtension(filename)), true); - }))).Wait(); + if (!File.Exists(Path.Combine(dir, filename))) + continue; + + Task.WhenAll(Directory.EnumerateFiles(dir, "*", new EnumerationOptions { RecurseSubdirectories = true }).Select(file => Task.Run(() => + { + var dst = Path.Combine(newDir, file.Substring(oldDir.Length + 1)); + Directory.CreateDirectory(Path.GetDirectoryName(dst)); + Console.WriteLine($"Copying {dst} ..."); + File.Copy(file, dst, true); + if (Path.GetFileName(file) == filename) + File.Copy(file, Path.Combine(Path.GetDirectoryName(dst), CmdAlias + Path.GetExtension(filename)), true); + }))).Wait(); + } } - var envPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User) - .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) - .Where(x => !x.Contains(nameof(CSharpScriptRunner))) + var envPath = (Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User) + ?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) + .Where(x => !x.Contains(nameof(CSharpScriptRunner))) ?? Array.Empty()) .Append(Path.GetDirectoryName(newPath)); Environment.SetEnvironmentVariable("Path", string.Join(';', envPath), EnvironmentVariableTarget.User); - Environment.SetEnvironmentVariable(nameof(CSharpScriptRunner)+"RuntimesDir", Path.GetDirectoryName(Path.GetDirectoryName(newPath)), EnvironmentVariableTarget.User); + Environment.SetEnvironmentVariable(nameof(CSharpScriptRunner) + "RuntimesDir", Path.GetDirectoryName(Path.GetDirectoryName(newPath)), EnvironmentVariableTarget.User); var filetype = ".csx"; @@ -254,20 +264,37 @@ static IEnumerable LoadPackages(string scriptPath, out InteractiveAssemb return buildReferences; } - static void RunScript(string[] args) + static void RunScript(string[] arguments) { - if (!File.Exists(args[0])) + IEnumerable args = arguments; + var runtimeExt = string.Empty; + while (args.FirstOrDefault()?.StartsWith('-') ?? false) + { + var arg = args.First(); + args = args.Skip(1); + if (arg.StartsWith("-r", StringComparison.OrdinalIgnoreCase)) + runtimeExt = arg.Substring(2); + else + { + WriteLine($"Argument {arg} is not recognized.", ConsoleColor.Red); + System.Threading.Thread.Sleep(5000); + return; + } + } + + var filePath = args.FirstOrDefault(); + if (!File.Exists(filePath)) { - WriteLine($"Script file '{args[0]}' does not exist.", ConsoleColor.Red); + WriteLine($"Script file '{filePath}' does not exist.", ConsoleColor.Red); System.Threading.Thread.Sleep(5000); return; } - var scriptPath = Path.GetFullPath(args[0]); - var runtimeExt = Path.GetExtension(Path.GetFileNameWithoutExtension(scriptPath)); + var scriptPath = Path.GetFullPath(filePath); + if (string.IsNullOrEmpty(runtimeExt)) + runtimeExt = Path.GetExtension(Path.GetFileNameWithoutExtension(scriptPath)).TrimStart('.'); if (!string.IsNullOrEmpty(runtimeExt)) { - runtimeExt = runtimeExt.Substring(1); var exePath = Process.GetCurrentProcess().MainModule.FileName; var filename = Path.GetFileName(exePath); var dir = Path.GetDirectoryName(exePath); @@ -278,7 +305,7 @@ static void RunScript(string[] args) exePath = Path.Combine(dir, runtimeExt, filename); if (File.Exists(exePath)) { - Process.Start(new ProcessStartInfo(exePath, string.Join(" ", args.Select(x => $"\"{x.Replace("\"", "\\\"")}\""))) { UseShellExecute = false }); + Process.Start(new ProcessStartInfo(exePath, string.Join(" ", args.Select(x => $"\"{x.Replace("\"", "\\\"")}\""))) { UseShellExecute = false }).WaitForExit(); return; } @@ -305,7 +332,7 @@ static void RunScript(string[] args) return; } - var assembly = Assembly.LoadFile(assemblyFile); + var assembly = Assembly.Load(File.ReadAllBytes(assemblyFile)); var type = assembly.GetType(config.Type); if (type == null) return; diff --git a/publish/win/install.bat b/publish/win/install.bat index d50607a..e9d0b14 100644 --- a/publish/win/install.bat +++ b/publish/win/install.bat @@ -1 +1 @@ -.\x64\CSharpScriptRunner.exe install \ No newline at end of file +.\x86\CSharpScriptRunner.exe install \ No newline at end of file From 071256b7d726fdab5125cfe37c9aa568f0e85f0d Mon Sep 17 00:00:00 2001 From: dev Date: Wed, 5 Aug 2020 07:22:09 +0200 Subject: [PATCH 18/43] Fix --- .github/workflows/main.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 202730a..6f4bfe3 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -8,11 +8,11 @@ jobs: runs-on: windows-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@main - name: Setup .NET Core SDK - uses: actions/setup-dotnet@v1.0.0 + uses: actions/setup-dotnet@v1 with: - version: 3.1.100 + dotnet-version: '3.1.x' - name: Build run: dotnet build -c Release @@ -23,11 +23,11 @@ jobs: needs: [build] steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@main - name: Setup .NET Core SDK - uses: actions/setup-dotnet@v1.0.0 + uses: actions/setup-dotnet@v1 with: - version: 3.1.100 + dotnet-version: '3.1.x' - name: Build run: | $version = "${{ github.ref }}" From f46cb4c5928141f377515da2d0eebb2c92db0075 Mon Sep 17 00:00:00 2001 From: dev Date: Mon, 4 Jan 2021 07:50:52 +0100 Subject: [PATCH 19/43] v1.0.8 --- .gitignore | 1 + CSharpScriptRunner.csproj | 25 ++++++++++++------------- publish/win/install.bat | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index 77e3653..79f13a8 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ publish/win/x64 publish/win/x86 publish/any/any .vscode +.vs diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index 6e10092..f52f677 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -1,9 +1,9 @@ - + C# Script Runner Exe - netcoreapp3.1 + net5.0-windows true true dev @@ -14,13 +14,15 @@ - - - - - - - + + + + + + + + + @@ -53,10 +55,7 @@ namespace CSharpScriptRunner } - + diff --git a/publish/win/install.bat b/publish/win/install.bat index e9d0b14..d50607a 100644 --- a/publish/win/install.bat +++ b/publish/win/install.bat @@ -1 +1 @@ -.\x86\CSharpScriptRunner.exe install \ No newline at end of file +.\x64\CSharpScriptRunner.exe install \ No newline at end of file From 17e1dc2eeb7e1cb9fbe408a3128bb9c2bcf9deff Mon Sep 17 00:00:00 2001 From: dev Date: Mon, 4 Jan 2021 07:55:21 +0100 Subject: [PATCH 20/43] Fix --- .github/workflows/main.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 6f4bfe3..3eb72c0 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -12,7 +12,7 @@ jobs: - name: Setup .NET Core SDK uses: actions/setup-dotnet@v1 with: - dotnet-version: '3.1.x' + dotnet-version: '5.0.x' - name: Build run: dotnet build -c Release @@ -27,7 +27,7 @@ jobs: - name: Setup .NET Core SDK uses: actions/setup-dotnet@v1 with: - dotnet-version: '3.1.x' + dotnet-version: '5.0.x' - name: Build run: | $version = "${{ github.ref }}" From c5d1f4785bfca294ae453b0edec94d6447f3fed9 Mon Sep 17 00:00:00 2001 From: dev Date: Mon, 4 Jan 2021 08:17:04 +0100 Subject: [PATCH 21/43] Fix --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 3eb72c0..9f4db2a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -32,7 +32,7 @@ jobs: run: | $version = "${{ github.ref }}" $version = $version.Substring(10) - echo "::set-env name=RELEASE_TAG::$version" + echo "RELEASE_TAG=$version" >> $GITHUB_ENV dotnet publish -c Release -r win-x86 -o ./publish/win/x86 -p:ReleaseTag=$version dotnet publish -c Release -r win-x64 -o ./publish/win/x64 -p:ReleaseTag=$version Compress-Archive -Path ./publish/win -DestinationPath ./publish/win.zip -CompressionLevel Optimal From 137e82edb5042105f02067144f1d86a7be69c441 Mon Sep 17 00:00:00 2001 From: dev Date: Mon, 4 Jan 2021 12:36:23 +0100 Subject: [PATCH 22/43] Fix --- CSharpScriptRunner.csproj | 1 + publish/win/install.bat | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index f52f677..539d4c6 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -4,6 +4,7 @@ C# Script Runner Exe net5.0-windows + true true true dev diff --git a/publish/win/install.bat b/publish/win/install.bat index d50607a..9e98cff 100644 --- a/publish/win/install.bat +++ b/publish/win/install.bat @@ -1 +1,2 @@ -.\x64\CSharpScriptRunner.exe install \ No newline at end of file +.\x64\CSharpScriptRunner.exe install +.\x64\CSharpScriptRunner.exe clear-cache \ No newline at end of file From f02edb5c10fba553ae4af51c14aec45615c7bdbf Mon Sep 17 00:00:00 2001 From: dev Date: Sat, 30 Jan 2021 09:43:26 +0100 Subject: [PATCH 23/43] Added install powershell --- Program.cs | 11 ++++++++--- Templates/Script.csx | 3 ++- Templates/ScriptUI.csx | 3 ++- Updates.cs | 7 ++++++- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/Program.cs b/Program.cs index efbef82..beeef99 100644 --- a/Program.cs +++ b/Program.cs @@ -76,7 +76,10 @@ static void PrintHelp() { var newRelease = Updates.CheckForNewRelease().Result; if (newRelease != default) + { Console.WriteLine($"A new release of {nameof(CSharpScriptRunner)} ({newRelease.Version}) is available at {newRelease.Url}"); + Console.WriteLine($"Install with powershell: {Updates.PowershellCommand}"); + } var exe = nameof(CSharpScriptRunner); Console.WriteLine($"Alias: {CmdAlias}"); @@ -406,10 +409,12 @@ static void CreateNew(string template) return; } - using (var res = typeof(Program).Assembly.GetManifestResourceStream(resName)) - using (var file = File.OpenWrite(filename)) + using (var res = new StreamReader(typeof(Program).Assembly.GetManifestResourceStream(resName))) + using (var file = new StreamWriter(File.OpenWrite(filename), Encoding.UTF8)) { - res.CopyTo(file); + var text = res.ReadToEnd(); + text = text.Replace("{PowershellCommand}", Updates.PowershellCommand); + file.Write(text); } WriteLine($"The file '{filename}' was created.", ConsoleColor.Green); diff --git a/Templates/Script.csx b/Templates/Script.csx index 9339ed6..b1e1ede 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -1,4 +1,5 @@ -// Run with CSharpScriptRunner: https://github.com/ArgusMagnus/CSharpScriptRunner/releases +// Run with CSharpScriptRunner: https://github.com/ArgusMagnus/CSharpScriptRunner/releases +// Install latest with PowerShell: {PowershellCommand} // // Arguments: // Arguments are received in the global variable 'Args' which is of type 'string[]'. diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index ec7ed6b..3f27283 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -1,4 +1,5 @@ -// Run with CSharpScriptRunner: https://github.com/ArgusMagnus/CSharpScriptRunner/releases +// Run with CSharpScriptRunner: https://github.com/ArgusMagnus/CSharpScriptRunner/releases +// Install latest with PowerShell: {PowershellCommand} // // Arguments: // Arguments are received in the global variable 'Args' which is of type 'string[]'. diff --git a/Updates.cs b/Updates.cs index 29a3e2d..b484601 100644 --- a/Updates.cs +++ b/Updates.cs @@ -19,9 +19,14 @@ sealed class ReleaseInfo static class Updates { + const string RequestUri = "https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest"; + public const string PowershellCommand = + @"$dir=md ""$Env:Temp\{$(New-Guid)}""; $bkp=$ProgressPreference; $ProgressPreference='SilentlyContinue'; Write-Host 'Downloading...'; Invoke-WebRequest (Invoke-RestMethod -Uri '" + RequestUri + + @"' | select -Expand assets | select-string -InputObject {$_.browser_download_url} -Pattern '-win\.zip$' | Select -Expand Line -First 1) -OutFile ""$dir\CSX.zip""; Write-Host 'Expanding archive...'; Expand-Archive -Path ""$dir\CSX.zip"" -DestinationPath ""$dir""; & ""$dir\win\x64\CSharpScriptRunner.exe"" 'install'; Remove-Item $dir -Recurse; $ProgressPreference=$bkp; Write-Host 'Done'"; + public static async Task CheckForNewRelease() { - const string RequestUri = "https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest"; + if (!BuildInfo.ReleaseTag.StartsWith('v') || !Version.TryParse(BuildInfo.ReleaseTag.Substring(1), out var version)) return default; From 320f86d303c267192267319ae6dc350e4b93cb9f Mon Sep 17 00:00:00 2001 From: dev Date: Sat, 30 Jan 2021 10:34:47 +0100 Subject: [PATCH 24/43] Fix --- Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Program.cs b/Program.cs index beeef99..315dfcf 100644 --- a/Program.cs +++ b/Program.cs @@ -164,7 +164,7 @@ static void Install(bool installInPlace) } WriteLine("Installation was successful.", ConsoleColor.Green); - System.Threading.Thread.Sleep(5000); + ClearCache(); } static string GetCacheFilenameBase(string filename) From 08dde9119786018452b47c35df2752e7d37f8e75 Mon Sep 17 00:00:00 2001 From: dev Date: Sat, 30 Jan 2021 11:18:12 +0100 Subject: [PATCH 25/43] Fixed Github action --- .github/workflows/main.yml | 6 +++--- Program.cs | 4 ++-- publish.ps1 | 4 ++-- publish/any/README | 1 - publish/win/install.bat | 2 -- 5 files changed, 7 insertions(+), 10 deletions(-) delete mode 100644 publish/any/README delete mode 100644 publish/win/install.bat diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 9f4db2a..d1159b3 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -32,9 +32,9 @@ jobs: run: | $version = "${{ github.ref }}" $version = $version.Substring(10) - echo "RELEASE_TAG=$version" >> $GITHUB_ENV - dotnet publish -c Release -r win-x86 -o ./publish/win/x86 -p:ReleaseTag=$version - dotnet publish -c Release -r win-x64 -o ./publish/win/x64 -p:ReleaseTag=$version + Add-Content -Path $env:GITHUB_ENV -Value "RELEASE_TAG=$version" -Encoding UTF8 + dotnet publish -c Release -r win-x86 -o ./publish/win/x86 -p:ReleaseTag=$version -p:PublishSingleFile=true + dotnet publish -c Release -r win-x64 -o ./publish/win/x64 -p:ReleaseTag=$version -p:PublishSingleFile=true Compress-Archive -Path ./publish/win -DestinationPath ./publish/win.zip -CompressionLevel Optimal dotnet publish -c Release -o ./publish/any -p:ReleaseTag=$version Compress-Archive -Path ./publish/any -DestinationPath ./publish/any.zip -CompressionLevel Optimal diff --git a/Program.cs b/Program.cs index 315dfcf..69cd649 100644 --- a/Program.cs +++ b/Program.cs @@ -129,8 +129,8 @@ static void Install(bool installInPlace) Directory.CreateDirectory(Path.GetDirectoryName(dst)); Console.WriteLine($"Copying {dst} ..."); File.Copy(file, dst, true); - if (Path.GetFileName(file) == filename) - File.Copy(file, Path.Combine(Path.GetDirectoryName(dst), CmdAlias + Path.GetExtension(filename)), true); + if (Path.GetFileName(file) == filename) + File.WriteAllText(Path.Combine(Path.GetDirectoryName(dst), $"{CmdAlias}.cmd"), $"@echo off & {filename} %*"); }))).Wait(); } } diff --git a/publish.ps1 b/publish.ps1 index 1e18283..9d8bf2c 100644 --- a/publish.ps1 +++ b/publish.ps1 @@ -1,3 +1,3 @@ -dotnet publish -c Release -r win-x86 -o publish/win/x86 -p:ReleaseTag=dev -dotnet publish -c Release -r win-x64 -o publish/win/x64 -p:ReleaseTag=dev +dotnet publish -c Release -r win-x86 -o publish/win/x86 -p:ReleaseTag=dev -p:PublishSingleFile=true +dotnet publish -c Release -r win-x64 -o publish/win/x64 -p:ReleaseTag=dev -p:PublishSingleFile=true dotnet publish -c Release -o publish/any/any -p:ReleaseTag=dev \ No newline at end of file diff --git a/publish/any/README b/publish/any/README deleted file mode 100644 index f5f5ef4..0000000 --- a/publish/any/README +++ /dev/null @@ -1 +0,0 @@ -Requires .NET Core 3.1 (or later) Runtime: https://docs.microsoft.com/en-us/dotnet/core/install/runtime \ No newline at end of file diff --git a/publish/win/install.bat b/publish/win/install.bat deleted file mode 100644 index 9e98cff..0000000 --- a/publish/win/install.bat +++ /dev/null @@ -1,2 +0,0 @@ -.\x64\CSharpScriptRunner.exe install -.\x64\CSharpScriptRunner.exe clear-cache \ No newline at end of file From 9a1740b5e0d1b7829b45f220bc1422e4d2c0acf0 Mon Sep 17 00:00:00 2001 From: dev Date: Sat, 30 Jan 2021 12:06:41 +0100 Subject: [PATCH 26/43] Fix --- .github/workflows/main.yml | 4 ++-- Program.cs | 14 +++++++------- publish.ps1 | 4 ++-- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index d1159b3..e1efaf9 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -33,8 +33,8 @@ jobs: $version = "${{ github.ref }}" $version = $version.Substring(10) Add-Content -Path $env:GITHUB_ENV -Value "RELEASE_TAG=$version" -Encoding UTF8 - dotnet publish -c Release -r win-x86 -o ./publish/win/x86 -p:ReleaseTag=$version -p:PublishSingleFile=true - dotnet publish -c Release -r win-x64 -o ./publish/win/x64 -p:ReleaseTag=$version -p:PublishSingleFile=true + dotnet publish -c Release -r win-x86 -o ./publish/win/x86 -p:ReleaseTag=$version + dotnet publish -c Release -r win-x64 -o ./publish/win/x64 -p:ReleaseTag=$version Compress-Archive -Path ./publish/win -DestinationPath ./publish/win.zip -CompressionLevel Optimal dotnet publish -c Release -o ./publish/any -p:ReleaseTag=$version Compress-Archive -Path ./publish/any -DestinationPath ./publish/any.zip -CompressionLevel Optimal diff --git a/Program.cs b/Program.cs index 69cd649..772ab50 100644 --- a/Program.cs +++ b/Program.cs @@ -123,15 +123,17 @@ static void Install(bool installInPlace) if (!File.Exists(Path.Combine(dir, filename))) continue; + var dstDir = Path.Combine(newDir, Path.GetFileName(dir)); Task.WhenAll(Directory.EnumerateFiles(dir, "*", new EnumerationOptions { RecurseSubdirectories = true }).Select(file => Task.Run(() => { - var dst = Path.Combine(newDir, file.Substring(oldDir.Length + 1)); + var dst = Path.Combine(dstDir, "bin", file.Substring(dir.Length + 1)); Directory.CreateDirectory(Path.GetDirectoryName(dst)); Console.WriteLine($"Copying {dst} ..."); File.Copy(file, dst, true); - if (Path.GetFileName(file) == filename) - File.WriteAllText(Path.Combine(Path.GetDirectoryName(dst), $"{CmdAlias}.cmd"), $"@echo off & {filename} %*"); }))).Wait(); + + File.WriteAllText(Path.Combine(dstDir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*"); + File.WriteAllText(Path.Combine(dstDir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*"); } } @@ -280,7 +282,6 @@ static void RunScript(string[] arguments) else { WriteLine($"Argument {arg} is not recognized.", ConsoleColor.Red); - System.Threading.Thread.Sleep(5000); return; } } @@ -289,7 +290,6 @@ static void RunScript(string[] arguments) if (!File.Exists(filePath)) { WriteLine($"Script file '{filePath}' does not exist.", ConsoleColor.Red); - System.Threading.Thread.Sleep(5000); return; } @@ -300,12 +300,12 @@ static void RunScript(string[] arguments) { var exePath = Process.GetCurrentProcess().MainModule.FileName; var filename = Path.GetFileName(exePath); - var dir = Path.GetDirectoryName(exePath); + var dir = Path.GetDirectoryName(Path.GetDirectoryName(exePath)); var runtimeDir = Path.GetFileName(dir); dir = Path.GetDirectoryName(dir); if (runtimeExt != runtimeDir) { - exePath = Path.Combine(dir, runtimeExt, filename); + exePath = Path.Combine(dir, runtimeExt, "bin", filename); if (File.Exists(exePath)) { Process.Start(new ProcessStartInfo(exePath, string.Join(" ", args.Select(x => $"\"{x.Replace("\"", "\\\"")}\""))) { UseShellExecute = false }).WaitForExit(); diff --git a/publish.ps1 b/publish.ps1 index 9d8bf2c..1e18283 100644 --- a/publish.ps1 +++ b/publish.ps1 @@ -1,3 +1,3 @@ -dotnet publish -c Release -r win-x86 -o publish/win/x86 -p:ReleaseTag=dev -p:PublishSingleFile=true -dotnet publish -c Release -r win-x64 -o publish/win/x64 -p:ReleaseTag=dev -p:PublishSingleFile=true +dotnet publish -c Release -r win-x86 -o publish/win/x86 -p:ReleaseTag=dev +dotnet publish -c Release -r win-x64 -o publish/win/x64 -p:ReleaseTag=dev dotnet publish -c Release -o publish/any/any -p:ReleaseTag=dev \ No newline at end of file From 1bcad7821fc23a35e80441ac2adc54f865b05d1f Mon Sep 17 00:00:00 2001 From: dev Date: Sat, 30 Jan 2021 12:25:06 +0100 Subject: [PATCH 27/43] Fix --- Program.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Program.cs b/Program.cs index 772ab50..5b4d9dd 100644 --- a/Program.cs +++ b/Program.cs @@ -116,7 +116,7 @@ static void Install(bool installInPlace) if (Directory.Exists(newDir)) Directory.Delete(newDir, true); Directory.CreateDirectory(newDir); - newPath = Path.Combine(newDir, runtimeDir, filename); + newPath = Path.Combine(newDir, runtimeDir, "bin", filename); foreach (var dir in Directory.EnumerateDirectories(oldDir)) { @@ -140,9 +140,9 @@ static void Install(bool installInPlace) var envPath = (Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User) ?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Where(x => !x.Contains(nameof(CSharpScriptRunner))) ?? Array.Empty()) - .Append(Path.GetDirectoryName(newPath)); + .Append(Path.GetDirectoryName(Path.GetDirectoryName(newPath))); Environment.SetEnvironmentVariable("Path", string.Join(';', envPath), EnvironmentVariableTarget.User); - Environment.SetEnvironmentVariable(nameof(CSharpScriptRunner) + "RuntimesDir", Path.GetDirectoryName(Path.GetDirectoryName(newPath)), EnvironmentVariableTarget.User); + Environment.SetEnvironmentVariable(nameof(CSharpScriptRunner) + "RuntimesDir", Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(newPath))), EnvironmentVariableTarget.User); var filetype = ".csx"; From e77c4762f0f070e2397b794d94acf2b296c5b28d Mon Sep 17 00:00:00 2001 From: developer Date: Fri, 19 Feb 2021 08:45:35 +0100 Subject: [PATCH 28/43] Installation error when instances are running --- Program.cs | 37 ++++++++++++++++++++++++++++++++---- Templates/Script.csx | 2 +- Templates/ScriptUI.csx | 2 +- Templates/vscode/launch.json | 5 ++--- 4 files changed, 37 insertions(+), 9 deletions(-) diff --git a/Program.cs b/Program.cs index 5b4d9dd..2719470 100644 --- a/Program.cs +++ b/Program.cs @@ -113,10 +113,26 @@ static void Install(bool installInPlace) else { var newDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner)); + newPath = Path.Combine(newDir, runtimeDir, "bin", filename); if (Directory.Exists(newDir)) - Directory.Delete(newDir, true); + { + WriteLine($"Removing previous installation..."); + try + { + if (File.Exists(newPath)) + File.Delete(newPath); + Directory.Delete(newDir, true); + } + catch (Exception ex) + { + WriteLine($"Operation failed with {ex.GetType().Name}: {ex.Message}", ConsoleColor.Red); + Console.WriteLine(); + var count = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length - 1; + WriteLine($"Please close all running instances ({count}) and try again:", ConsoleColor.Red); + return; + } + } Directory.CreateDirectory(newDir); - newPath = Path.Combine(newDir, runtimeDir, "bin", filename); foreach (var dir in Directory.EnumerateDirectories(oldDir)) { @@ -126,12 +142,12 @@ static void Install(bool installInPlace) var dstDir = Path.Combine(newDir, Path.GetFileName(dir)); Task.WhenAll(Directory.EnumerateFiles(dir, "*", new EnumerationOptions { RecurseSubdirectories = true }).Select(file => Task.Run(() => { - var dst = Path.Combine(dstDir, "bin", file.Substring(dir.Length + 1)); + var dst = Path.Combine(dstDir, "bin", file.Substring(dir.Length + 1)); Directory.CreateDirectory(Path.GetDirectoryName(dst)); Console.WriteLine($"Copying {dst} ..."); File.Copy(file, dst, true); }))).Wait(); - + File.WriteAllText(Path.Combine(dstDir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*"); File.WriteAllText(Path.Combine(dstDir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*"); } @@ -146,6 +162,7 @@ static void Install(bool installInPlace) var filetype = ".csx"; + // https://docs.microsoft.com/en-us/windows/win32/shell/context-menu-handlers using (var regKeyExt = Registry.CurrentUser.CreateSubKey($@"Software\Classes\{filetype}", true)) { var tmp = regKeyExt.GetValue(string.Empty) as string; @@ -165,6 +182,15 @@ static void Install(bool installInPlace) regKeyCommand.SetValue(string.Empty, $"\"{newPath}\" \"%1\""); } + using (var regKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Classes\*\shell\CSharpScriptRunner", true)) + using (var regKeyCommand = regKey.CreateSubKey("command", true)) + { + regKey.SetValue(string.Empty, "C# Skript ausführen"); + regKey.SetValue("AppliesTo", "System.FileExtension:\"csx\"", RegistryValueKind.String); + regKey.SetValue("Position", "Top", RegistryValueKind.String); + regKeyCommand.SetValue(string.Empty, $"\"{newPath}\" \"%1\""); + } + WriteLine("Installation was successful.", ConsoleColor.Green); ClearCache(); } @@ -329,7 +355,10 @@ static void RunScript(string[] arguments) // Check for new release only when compiling var newRelease = Updates.CheckForNewRelease().Result; if (newRelease != default) + { Console.WriteLine($"A new release of {nameof(CSharpScriptRunner)} ({newRelease.Version}) is available at {newRelease.Url}"); + Console.WriteLine($"Install with powershell: {Updates.PowershellCommand}"); + } if (!TryBuild(scriptPath, assemblyFile, hashFile, configFile, scriptHash, buildReferences, out config)) return; diff --git a/Templates/Script.csx b/Templates/Script.csx index b1e1ede..1ec914d 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -29,7 +29,7 @@ foreach (var arg in Script.ParseArguments(Args)) Script.WriteLine("Press Enter to exit"); Console.ReadLine(); -return; // End of script +return 0; // End of script #region Utilities diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index 3f27283..683b3c4 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -54,7 +54,7 @@ var window = (Window)XamlReader.Parse(@" window.DataContext = new Command(() => MessageBox.Show("Hello World!")); window.ShowDialog(); -return; // End of script +return 0; // End of script #region Utilities diff --git a/Templates/vscode/launch.json b/Templates/vscode/launch.json index 81d1625..ed37232 100644 --- a/Templates/vscode/launch.json +++ b/Templates/vscode/launch.json @@ -8,9 +8,8 @@ { "name": ".NET Core Launch (console)", "type": "coreclr", - "request": "launch", - "program": "CSharpScriptRunner", - //"program": "${env:CSharpScriptRunnerRuntimesDir}/x64/CSharpScriptRunner", + "request": "launch", + "program": "${env:CSharpScriptRunnerRuntimesDir}/x64/bin/CSharpScriptRunner", "args": [ "${file}" ], "cwd": "${workspaceFolder}", "console": "internalConsole", From 9c22fb12af1aea57e572f3b60374bfcbd4ef5c79 Mon Sep 17 00:00:00 2001 From: developer Date: Sat, 24 Apr 2021 21:16:59 +0200 Subject: [PATCH 29/43] Fix --- Program.cs | 115 +++++++++++++++++++++++++++++++---------- Templates/Script.csx | 118 +++++++++++++++++++++---------------------- Updates.cs | 2 - 3 files changed, 146 insertions(+), 89 deletions(-) diff --git a/Program.cs b/Program.cs index 2719470..edff824 100644 --- a/Program.cs +++ b/Program.cs @@ -10,6 +10,7 @@ using System.Security.Cryptography; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Collections.Concurrent; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis; @@ -18,6 +19,7 @@ using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.CSharp; +using System.Threading; namespace CSharpScriptRunner { @@ -35,20 +37,60 @@ static class Program static class Verbs { + public const string Version = "--version"; public const string Install = "install"; public const string New = "new"; public const string ClearCache = "clear-cache"; public const string InitVSCode = "init-vscode"; } + sealed class CurrentThreadSynchronizationContext : System.Threading.SynchronizationContext + { + readonly BlockingCollection<(SendOrPostCallback Callback, object State, ManualResetEventSlim Signal)> _queue = new(); + + CurrentThreadSynchronizationContext() { } + + public override void Send(SendOrPostCallback d, object state) + { + var signal = new ManualResetEventSlim(false); + _queue.Add((d, state, signal)); + signal.Wait(); + } + + public override void Post(SendOrPostCallback d, object state) + { + _queue.Add((d, state, null)); + } + + public static void Run(Func main) + { + var syncCtx = new CurrentThreadSynchronizationContext(); + SynchronizationContext.SetSynchronizationContext(syncCtx); + var mainTask = main(); + mainTask.ContinueWith(t => syncCtx._queue.CompleteAdding()); + foreach (var item in syncCtx._queue.GetConsumingEnumerable()) + { + item.Callback(item.State); + item.Signal?.Set(); + } + mainTask.Wait(); + } + } + [STAThread] + // Must run on STA thread (for WinForms/WPF support) static void Main(string[] args) + { + CurrentThreadSynchronizationContext.Run(() => MainAsync(args)); + } + + static async Task MainAsync(string[] args) { Console.WriteLine($"{nameof(CSharpScriptRunner)}, {BuildInfo.ReleaseTag}"); if (args == null || args.Length == 0) { - PrintHelp(); + await PrintHelp(); return; } @@ -56,11 +98,12 @@ static void Main(string[] args) { switch (args[0].ToLowerInvariant()) { - case Verbs.Install: Install(args.Length > 1 ? string.Equals(args[1], "inplace", StringComparison.OrdinalIgnoreCase) : false); break; + case Verbs.Version: break; + case Verbs.Install: await Install(args.Length > 1 ? string.Equals(args[1], "inplace", StringComparison.OrdinalIgnoreCase) : false); break; case Verbs.New: CreateNew(args.Length > 1 ? args[1] : null); break; - case Verbs.ClearCache: ClearCache(); break; + case Verbs.ClearCache: await ClearCache(); break; case Verbs.InitVSCode: InitVSCode(); break; - default: RunScript(args); break; + default: await RunScript(args); break; } } catch (Exception ex) @@ -68,13 +111,12 @@ static void Main(string[] args) if (ex is AggregateException aggregateException) ex = aggregateException.InnerException; WriteLine(ex.ToString(), ConsoleColor.Red); - System.Threading.Thread.Sleep(5000); } } - static void PrintHelp() + static async Task PrintHelp() { - var newRelease = Updates.CheckForNewRelease().Result; + var newRelease = await Updates.CheckForNewRelease(); if (newRelease != default) { Console.WriteLine($"A new release of {nameof(CSharpScriptRunner)} ({newRelease.Version}) is available at {newRelease.Url}"); @@ -97,7 +139,7 @@ static void PrintHelp() Console.WriteLine($" Cleares the cache of previously compiled scripts."); } - static void Install(bool installInPlace) + static async Task Install(bool installInPlace) { var oldPath = Process.GetCurrentProcess().MainModule.FileName; var newPath = oldPath; @@ -140,13 +182,13 @@ static void Install(bool installInPlace) continue; var dstDir = Path.Combine(newDir, Path.GetFileName(dir)); - Task.WhenAll(Directory.EnumerateFiles(dir, "*", new EnumerationOptions { RecurseSubdirectories = true }).Select(file => Task.Run(() => + await Task.WhenAll(Directory.EnumerateFiles(dir, "*", new EnumerationOptions { RecurseSubdirectories = true }).Select(file => Task.Run(() => { var dst = Path.Combine(dstDir, "bin", file.Substring(dir.Length + 1)); Directory.CreateDirectory(Path.GetDirectoryName(dst)); Console.WriteLine($"Copying {dst} ..."); File.Copy(file, dst, true); - }))).Wait(); + }))); File.WriteAllText(Path.Combine(dstDir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*"); File.WriteAllText(Path.Combine(dstDir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*"); @@ -192,7 +234,7 @@ static void Install(bool installInPlace) } WriteLine("Installation was successful.", ConsoleColor.Green); - ClearCache(); + await ClearCache(); } static string GetCacheFilenameBase(string filename) @@ -261,10 +303,7 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st var result = compilation.Emit(stream, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded)); PrintCompilationDiagnostics(result, lines); if (!result.Success) - { - System.Threading.Thread.Sleep(5000); - return false; - } + return false; } File.WriteAllBytes(hashFile, scriptHash); @@ -281,21 +320,22 @@ static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, st return true; } - static IEnumerable LoadPackages(string scriptPath, out InteractiveAssemblyLoader assemblyLoader) + static async Task<(IEnumerable BuildReferences, InteractiveAssemblyLoader assemblyLoader1)> LoadPackages(string scriptPath) { var buildReferences = new HashSet(StringComparer.OrdinalIgnoreCase); var runtimeReferences = new HashSet(StringComparer.OrdinalIgnoreCase); var matches = Regex.Matches(File.ReadAllText(scriptPath), NuGetReferenceRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase); foreach (Match match in matches) - NuGet.LoadPackage(match.Groups["name"].Value, match.Groups["version"].Value, buildReferences, runtimeReferences).Wait(); + await NuGet.LoadPackage(match.Groups["name"].Value, match.Groups["version"].Value, buildReferences, runtimeReferences); - assemblyLoader = new InteractiveAssemblyLoader(); + var assemblyLoader = new InteractiveAssemblyLoader(); foreach (var path in runtimeReferences) assemblyLoader.RegisterDependency(Assembly.LoadFrom(path)); - return buildReferences; + return (buildReferences, assemblyLoader); } - static void RunScript(string[] arguments) + + static async Task RunScript(string[] arguments) { IEnumerable args = arguments; var runtimeExt = string.Empty; @@ -342,7 +382,7 @@ static void RunScript(string[] arguments) } } - var buildReferences = LoadPackages(scriptPath, out var assemblyLoader); + var (buildReferences, assemblyLoader) = await LoadPackages(scriptPath); var cacheFileBase = GetCacheFilenameBase(scriptPath); var assemblyFile = cacheFileBase + ".dll"; @@ -353,7 +393,7 @@ static void RunScript(string[] arguments) if (!TryGetCache(assemblyFile, hashFile, configFile, scriptHash, out var config)) { // Check for new release only when compiling - var newRelease = Updates.CheckForNewRelease().Result; + var newRelease = await Updates.CheckForNewRelease(); if (newRelease != default) { Console.WriteLine($"A new release of {nameof(CSharpScriptRunner)} ({newRelease.Version}) is available at {newRelease.Url}"); @@ -372,9 +412,9 @@ static void RunScript(string[] arguments) if (entryPoint == null) return; - Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath); + // Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath); var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), assemblyLoader } }); - task.Wait(); + await task; } static void PrintCompilationDiagnostics(EmitResult result, string[] lines) @@ -413,6 +453,23 @@ static void PrintCompilationDiagnostics(EmitResult result, string[] lines) static void CreateNew(string template) { + // Script method: + // public static bool ExitAndUpdateEngine() + // { + // var count = System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length - 1; + // if (count > 0) + // { + // Script.WriteLines(new[] { + // "The script engine cannot be updated, while there are running script instances.", + // $"There are currently {count} running script instances." }, ConsoleColor.Yellow); + // return false; + // } + // var cmd = "{PowershellCommandEscaped}".Replace("\"", "\\\""); + // System.Diagnostics.Process.Start(new ProcessStartInfo { FileName = "powershell", Arguments = $"-NoExit -Command \"{cmd}\"", UseShellExecute = true }); + // Environment.Exit(0); + // return true; + // } + var templates = typeof(Program).Assembly.GetManifestResourceNames() .Where(x => string.Equals(Path.GetExtension(x), ".csx", StringComparison.OrdinalIgnoreCase)) .ToDictionary(x => Path.GetExtension(Path.GetFileNameWithoutExtension(x)).Substring(1), StringComparer.OrdinalIgnoreCase); @@ -442,24 +499,26 @@ static void CreateNew(string template) using (var file = new StreamWriter(File.OpenWrite(filename), Encoding.UTF8)) { var text = res.ReadToEnd(); - text = text.Replace("{PowershellCommand}", Updates.PowershellCommand); + text = text + .Replace("{PowershellCommand}", Updates.PowershellCommand) + .Replace("{PowershellCommandEscaped}", Updates.PowershellCommand.Replace("\\", "\\\\").Replace("\"", "\\\"")); file.Write(text); } WriteLine($"The file '{filename}' was created.", ConsoleColor.Green); } - static void ClearCache() + static async Task ClearCache() { if (!Directory.Exists(CachePath)) return; - Task.WhenAll(Directory.EnumerateFiles(CachePath).Select(path => Task.Run(() => + await Task.WhenAll(Directory.EnumerateFiles(CachePath).Select(path => Task.Run(() => { try { File.Delete(path); } catch (IOException) { } catch (UnauthorizedAccessException) { } - }))).Wait(); + }))); WriteLine("Cache cleared", ConsoleColor.Green); } diff --git a/Templates/Script.csx b/Templates/Script.csx index 1ec914d..eff273d 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; Script.WriteLine($"Executing script '{Script.ScriptPath}'...", ConsoleColor.Green); Script.WriteLine("Hallo from script"); @@ -35,75 +36,74 @@ return 0; // End of script public static class Script { - static string GetScriptPath([System.Runtime.CompilerServices.CallerFilePath] string path = null) => path; - public static string ScriptPath { get; } = GetScriptPath(); - public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath); - public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath); + static string GetScriptPath([System.Runtime.CompilerServices.CallerFilePath] string path = null) => path; + public static string ScriptPath { get; } = GetScriptPath(); + public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath); + public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath); - static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; + static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; - [System.Runtime.InteropServices.DllImport("user32.dll")] - static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); - const int SW_HIDE = 0; - const int SW_SHOW = 5; + const int SW_HIDE = 0; + const int SW_SHOW = 5; - public static void HideConsole() { IsConsoleHidden = true; ShowWindow(_consoleWindow, SW_HIDE); } - public static void ShowConsole() { IsConsoleHidden = false; ShowWindow(_consoleWindow, SW_SHOW); } - public static bool IsConsoleHidden { get; private set; } = false; + public static void HideConsole() { IsConsoleHidden = true; ShowWindow(_consoleWindow, SW_HIDE); } + public static void ShowConsole() { IsConsoleHidden = false; ShowWindow(_consoleWindow, SW_SHOW); } + public static bool IsConsoleHidden { get; private set; } = false; - public static void WriteLine(string text, ConsoleColor color = (ConsoleColor)(-1)) - { - var c = Console.ForegroundColor; - if ((int)color > -1) - Console.ForegroundColor = color; - Console.WriteLine(text); - Console.ForegroundColor = c; - } - - public static void WriteLines(IEnumerable lines, ConsoleColor color = (ConsoleColor)(-1)) + static readonly object _lock = new(); + static void DoWrite(ConsoleColor color, Action action) { - var c = Console.ForegroundColor; - if ((int)color > -1) + if ((int)color == -1) + { + action(); + return; + } + + lock (_lock) + { + var c = Console.ForegroundColor; Console.ForegroundColor = color; - foreach (var line in lines) - Console.WriteLine(line); - Console.ForegroundColor = c; + action(); + Console.ForegroundColor = c; + } } + public static void WriteLine(string text, ConsoleColor color = (ConsoleColor)(-1)) + => DoWrite(color, () => Console.WriteLine(text)); + + public static void WriteLines(IEnumerable lines, ConsoleColor color = (ConsoleColor)(-1)) + => DoWrite(color, () => { foreach (var line in lines) Console.WriteLine(line); }); + public static void Write(string text, ConsoleColor color = (ConsoleColor)(-1)) - { - var c = Console.ForegroundColor; - if ((int)color > -1) - Console.ForegroundColor = color; - Console.Write(text); - Console.ForegroundColor = c; - } - - public static IDictionary ParseArguments(IEnumerable args) - { - var arguments = new Dictionary(StringComparer.OrdinalIgnoreCase); - string key = null; - foreach (var value in args) - { - if (value.StartsWith("-")) - { - if (key != null) - arguments[key] = true.ToString(); - key = value.Substring(1); - } - else - { - if (key == null) - throw new ArgumentNullException(value, "The parameter is missing its name."); - arguments[key] = value; - key = null; - } - } - if (key != null) - arguments[key] = true.ToString(); - return arguments; - } + => DoWrite(color, () => Console.Write(text)); + + public static IDictionary ParseArguments(IEnumerable args) + { + var arguments = new Dictionary(StringComparer.OrdinalIgnoreCase); + string key = null; + foreach (var value in args) + { + if (value.StartsWith("-")) + { + if (key != null) + arguments[key] = true.ToString(); + key = value.Substring(1); + } + else + { + if (key == null) + throw new ArgumentNullException(value, "The parameter is missing its name."); + arguments[key] = value; + key = null; + } + } + if (key != null) + arguments[key] = true.ToString(); + return arguments; + } } #endregion \ No newline at end of file diff --git a/Updates.cs b/Updates.cs index b484601..44a4d88 100644 --- a/Updates.cs +++ b/Updates.cs @@ -26,8 +26,6 @@ static class Updates public static async Task CheckForNewRelease() { - - if (!BuildInfo.ReleaseTag.StartsWith('v') || !Version.TryParse(BuildInfo.ReleaseTag.Substring(1), out var version)) return default; From 307a25fa372bc6086fb3189861b7db02ae5cbad5 Mon Sep 17 00:00:00 2001 From: developer Date: Tue, 27 Apr 2021 13:27:53 +0200 Subject: [PATCH 30/43] update command --- .github/workflows/main.yml | 14 +- Program.ClearCache.cs | 24 + ...ram.CurrentThreadSynchronizationContext.cs | 46 ++ Program.InitVSCode.cs | 43 ++ Program.Install.cs | 110 ++++ Program.New.cs | 67 +++ Program.RunScript.cs | 234 ++++++++ Program.Update.cs | 127 +++++ Program.cs | 507 ++---------------- Templates/Script.csx | 3 +- Templates/ScriptUI.csx | 128 ++--- Updates.cs | 71 +-- 12 files changed, 799 insertions(+), 575 deletions(-) create mode 100644 Program.ClearCache.cs create mode 100644 Program.CurrentThreadSynchronizationContext.cs create mode 100644 Program.InitVSCode.cs create mode 100644 Program.Install.cs create mode 100644 Program.New.cs create mode 100644 Program.RunScript.cs create mode 100644 Program.Update.cs diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index e1efaf9..c3c934a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -35,9 +35,7 @@ jobs: Add-Content -Path $env:GITHUB_ENV -Value "RELEASE_TAG=$version" -Encoding UTF8 dotnet publish -c Release -r win-x86 -o ./publish/win/x86 -p:ReleaseTag=$version dotnet publish -c Release -r win-x64 -o ./publish/win/x64 -p:ReleaseTag=$version - Compress-Archive -Path ./publish/win -DestinationPath ./publish/win.zip -CompressionLevel Optimal - dotnet publish -c Release -o ./publish/any -p:ReleaseTag=$version - Compress-Archive -Path ./publish/any -DestinationPath ./publish/any.zip -CompressionLevel Optimal + Compress-Archive -Path ./publish/win/* -DestinationPath ./publish/win.zip -CompressionLevel Optimal - name: Create Release id: create_release uses: actions/create-release@v1.0.0 @@ -58,13 +56,3 @@ jobs: asset_path: ./publish/win.zip asset_name: CSharpScriptRunner-${{ env.RELEASE_TAG }}-win.zip asset_content_type: application/zip - - name: Upload Release Asset (any) - id: upload-release-asset-any - uses: actions/upload-release-asset@v1.0.1 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ steps.create_release.outputs.upload_url }} - asset_path: ./publish/any.zip - asset_name: CSharpScriptRunner-${{ env.RELEASE_TAG }}-any.zip - asset_content_type: application/zip diff --git a/Program.ClearCache.cs b/Program.ClearCache.cs new file mode 100644 index 0000000..6f0b5b5 --- /dev/null +++ b/Program.ClearCache.cs @@ -0,0 +1,24 @@ +using System; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace CSharpScriptRunner +{ + static partial class Program + { + static async Task ClearCache() + { + if (!Directory.Exists(CachePath)) + return; + + await Task.WhenAll(Directory.EnumerateFiles(CachePath).Select(path => Task.Run(() => + { + try { File.Delete(path); } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + }))); + WriteLine("Cache cleared", ConsoleColor.Green); + } + } +} \ No newline at end of file diff --git a/Program.CurrentThreadSynchronizationContext.cs b/Program.CurrentThreadSynchronizationContext.cs new file mode 100644 index 0000000..792eac5 --- /dev/null +++ b/Program.CurrentThreadSynchronizationContext.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Concurrent; +using System.Threading.Tasks; +using System.Threading; + +namespace CSharpScriptRunner +{ + static partial class Program + { + sealed class CurrentThreadSynchronizationContext : System.Threading.SynchronizationContext + { + readonly BlockingCollection<(SendOrPostCallback Callback, object State)> _queue = new(); + // readonly BlockingCollection<(SendOrPostCallback Callback, object State, ManualResetEventSlim Signal)> _queue = new(); + + CurrentThreadSynchronizationContext() { } + + public override void Send(SendOrPostCallback d, object state) + { + // var signal = new ManualResetEventSlim(false); + // _queue.Add((d, state, signal)); + // signal.Wait(); + throw new InvalidOperationException(); + } + + public override void Post(SendOrPostCallback d, object state) + { + _queue.Add((d, state)); + // _queue.Add((d, state, null)); + } + + public static int Run(Func> main) + { + var syncCtx = new CurrentThreadSynchronizationContext(); + SynchronizationContext.SetSynchronizationContext(syncCtx); + var mainTask = main(); + mainTask.ContinueWith(t => syncCtx._queue.CompleteAdding()); + foreach (var item in syncCtx._queue.GetConsumingEnumerable()) + { + item.Callback(item.State); + // item.Signal?.Set(); + } + return (int)mainTask.Result; + } + } + } +} diff --git a/Program.InitVSCode.cs b/Program.InitVSCode.cs new file mode 100644 index 0000000..c23b986 --- /dev/null +++ b/Program.InitVSCode.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using System.Linq; + +namespace CSharpScriptRunner +{ + static partial class Program + { + static void InitVSCode() + { + const string VSCodeDir = ".vscode"; + const string Filter = ".Templates.vscode."; + + var templates = typeof(Program).Assembly.GetManifestResourceNames() + .Select(x => (i: x.IndexOf(Filter), s: x)) + .Where(x => x.i > -1) + .Select(x => (name: x.s, File: Path.Combine(VSCodeDir, x.s.Substring(x.i + Filter.Length)))); + + var dir = new DirectoryInfo(VSCodeDir); + if (!dir.Exists) + { + dir.Create(); + //dir.Attributes |= FileAttributes.Hidden; + } + + foreach (var template in templates) + { + if (File.Exists(template.File)) + { + WriteLine($"File '{template.File}' already exists.", ConsoleColor.Yellow); + continue; + } + + using (var stream = typeof(Program).Assembly.GetManifestResourceStream(template.name)) + using (var file = File.OpenWrite(template.File)) + { + WriteLine($"Creating file '{template.File}'...", ConsoleColor.Green); + stream.CopyTo(file); + } + } + } + } +} \ No newline at end of file diff --git a/Program.Install.cs b/Program.Install.cs new file mode 100644 index 0000000..7135c90 --- /dev/null +++ b/Program.Install.cs @@ -0,0 +1,110 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Win32; + +namespace CSharpScriptRunner +{ + static partial class Program + { + static async Task Install(bool installInPlace) + { + var oldPath = Process.GetCurrentProcess().MainModule.FileName; + var newPath = oldPath; + var filename = Path.GetFileName(oldPath); + var oldDir = Path.GetDirectoryName(oldPath); + var runtimeDir = Path.GetFileName(oldDir); + oldDir = Path.GetDirectoryName(oldDir); + var newDir = oldDir; + + if (!installInPlace) + { + newDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner), BuildInfo.ReleaseTag); + newPath = Path.Combine(newDir, runtimeDir, "bin", filename); + if (Directory.Exists(newDir)) + { + WriteLine($"Removing previous installation..."); + try + { + if (File.Exists(newPath)) + File.Delete(newPath); + Directory.Delete(newDir, true); + } + catch (Exception ex) + { + WriteLine($"Operation failed with {ex.GetType().Name}: {ex.Message}", ConsoleColor.Red); + Console.WriteLine(); + var count = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length - 1; + WriteLine($"Please close all running instances ({count}) and try again:", ConsoleColor.Red); + return; + } + } + Directory.CreateDirectory(newDir); + } + + foreach (var dir in Directory.EnumerateDirectories(oldDir)) + { + if (!File.Exists(Path.Combine(dir, filename))) + continue; + + var dstDir = Path.Combine(newDir, Path.GetFileName(dir)); + if (!installInPlace) + { + await Task.WhenAll(Directory.EnumerateFiles(dir, "*", new EnumerationOptions { RecurseSubdirectories = true }).Select(file => Task.Run(() => + { + var dst = Path.Combine(dstDir, "bin", file.Substring(dir.Length + 1)); + Directory.CreateDirectory(Path.GetDirectoryName(dst)); + Console.WriteLine($"Copying {dst} ..."); + File.Copy(file, dst, true); + }))); + } + + File.WriteAllText(Path.Combine(dstDir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*"); + File.WriteAllText(Path.Combine(dstDir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*"); + } + + var envPath = (Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User) + ?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) + .Where(x => !x.Contains(nameof(CSharpScriptRunner))) ?? Array.Empty()) + .Append(Path.GetDirectoryName(Path.GetDirectoryName(newPath))); + Environment.SetEnvironmentVariable("Path", string.Join(';', envPath), EnvironmentVariableTarget.User); + Environment.SetEnvironmentVariable(nameof(CSharpScriptRunner) + "RuntimesDir", Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(newPath))), EnvironmentVariableTarget.User); + + var filetype = ".csx"; + + // https://docs.microsoft.com/en-us/windows/win32/shell/context-menu-handlers + using (var regKeyExt = Registry.CurrentUser.CreateSubKey($@"Software\Classes\{filetype}", true)) + { + var tmp = regKeyExt.GetValue(string.Empty) as string; + if (!string.IsNullOrEmpty(tmp)) + filetype = tmp; + else + { + filetype = filetype.Substring(1) + "_auto_file"; + regKeyExt.SetValue(string.Empty, filetype); + } + } + + using (var regKey = Registry.CurrentUser.CreateSubKey($@"Software\Classes\{filetype}\shell\execute", true)) + using (var regKeyCommand = regKey.CreateSubKey("command", true)) + { + regKey.SetValue(string.Empty, "C# Skript ausführen"); + regKeyCommand.SetValue(string.Empty, $"\"{newPath}\" \"%1\""); + } + + using (var regKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Classes\*\shell\CSharpScriptRunner", true)) + using (var regKeyCommand = regKey.CreateSubKey("command", true)) + { + regKey.SetValue(string.Empty, "C# Skript ausführen"); + regKey.SetValue("AppliesTo", "System.FileExtension:\"csx\"", RegistryValueKind.String); + regKey.SetValue("Position", "Top", RegistryValueKind.String); + regKeyCommand.SetValue(string.Empty, $"\"{newPath}\" \"%1\""); + } + + WriteLine("Installation was successful.", ConsoleColor.Green); + await ClearCache(); + } + } +} \ No newline at end of file diff --git a/Program.New.cs b/Program.New.cs new file mode 100644 index 0000000..c455d57 --- /dev/null +++ b/Program.New.cs @@ -0,0 +1,67 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; + +namespace CSharpScriptRunner +{ + static partial class Program + { + static void CreateNew(string template) + { + // Script method: + // public static bool ExitAndUpdateEngine() + // { + // var count = System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length - 1; + // if (count > 0) + // { + // Script.WriteLines(new[] { + // "The script engine cannot be updated, while there are running script instances.", + // $"There are currently {count} running script instances." }, ConsoleColor.Yellow); + // return false; + // } + // var cmd = "{PowershellCommandEscaped}".Replace("\"", "\\\""); + // System.Diagnostics.Process.Start(new ProcessStartInfo { FileName = "powershell", Arguments = $"-NoExit -Command \"{cmd}\"", UseShellExecute = true }); + // Environment.Exit(0); + // return true; + // } + + var templates = typeof(Program).Assembly.GetManifestResourceNames() + .Where(x => string.Equals(Path.GetExtension(x), ".csx", StringComparison.OrdinalIgnoreCase)) + .ToDictionary(x => Path.GetExtension(Path.GetFileNameWithoutExtension(x)).Substring(1), StringComparer.OrdinalIgnoreCase); + + if (template == null) + { + Console.Write("Available templates: "); + Console.WriteLine(string.Join(", ", templates.Keys)); + Console.Write("Enter the name of the template you wish to create: "); + template = Console.ReadLine().Trim(); + } + + if (!templates.TryGetValue(template, out var resName)) + { + WriteLine($"The template '{template}' does not exists.", ConsoleColor.Red); + return; + } + + var filename = template + ".csx"; + if (File.Exists(filename)) + { + WriteLine($"The file '{filename} already exists.", ConsoleColor.Red); + return; + } + + using (var res = new StreamReader(typeof(Program).Assembly.GetManifestResourceStream(resName))) + using (var file = new StreamWriter(File.OpenWrite(filename), Encoding.UTF8)) + { + var text = res.ReadToEnd(); + text = text + .Replace("{PowershellCommand}", PowershellUpdateCommand) + .Replace("{PowershellCommandEscaped}", PowershellUpdateCommand.Replace("\\", "\\\\").Replace("\"", "\\\"")); + file.Write(text); + } + + WriteLine($"The file '{filename}' was created.", ConsoleColor.Green); + } + } +} \ No newline at end of file diff --git a/Program.RunScript.cs b/Program.RunScript.cs new file mode 100644 index 0000000..3a0d962 --- /dev/null +++ b/Program.RunScript.cs @@ -0,0 +1,234 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Scripting; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Scripting; +using Microsoft.CodeAnalysis.Scripting.Hosting; + +namespace CSharpScriptRunner +{ + static partial class Program + { + sealed class Config + { + public string Type { get; set; } + public string Method { get; set; } + } + + static async Task RunScript(string[] arguments) + { + const string NuGetReferenceRegex = @"^\s*#r\s+""\s*nuget:\s*(?[\w\d.-]+)\s*\/\s*(?[\w\d.-]+)\s*""\s*$"; + + IEnumerable args = arguments; + var runtimeExt = string.Empty; + while (args.FirstOrDefault()?.StartsWith('-') ?? false) + { + var arg = args.First(); + args = args.Skip(1); + if (arg.StartsWith("-r", StringComparison.OrdinalIgnoreCase)) + runtimeExt = arg.Substring(2); + else + { + WriteLine($"Argument {arg} is not recognized.", ConsoleColor.Red); + return ErrorCodes.UnrecognizedArgument; + } + } + + var filePath = args.FirstOrDefault(); + if (!File.Exists(filePath)) + { + WriteLine($"Script file '{filePath}' does not exist.", ConsoleColor.Red); + return ErrorCodes.ScriptFileDoesNotExist; + } + + var scriptPath = Path.GetFullPath(filePath); + if (string.IsNullOrEmpty(runtimeExt)) + runtimeExt = Path.GetExtension(Path.GetFileNameWithoutExtension(scriptPath)).TrimStart('.'); + if (!string.IsNullOrEmpty(runtimeExt)) + { + var exePath = Process.GetCurrentProcess().MainModule.FileName; + var filename = Path.GetFileName(exePath); + var dir = Path.GetDirectoryName(Path.GetDirectoryName(exePath)); + var runtimeDir = Path.GetFileName(dir); + dir = Path.GetDirectoryName(dir); + if (runtimeExt != runtimeDir) + { + exePath = Path.Combine(dir, runtimeExt, "bin", filename); + if (File.Exists(exePath)) + { + using var process = Process.Start(new ProcessStartInfo(exePath, string.Join(" ", args.Select(x => $"\"{x.Replace("\"", "\\\"")}\""))) { UseShellExecute = false }); + await process.WaitForExitAsync(); + return (ErrorCodes)process.ExitCode; + } + + WriteLine($"Warning: Runtime '{runtimeExt}' was not found. Proceeding anyway...", ConsoleColor.Yellow); + } + } + + var (buildReferences, assemblyLoader) = await LoadPackages(scriptPath); + + var cacheFileBase = GetCacheFilenameBase(scriptPath); + var assemblyFile = cacheFileBase + ".dll"; + var hashFile = cacheFileBase + ".hash"; + var configFile = cacheFileBase + ".json"; + var scriptHash = GetFileHash(scriptPath); + + if (!TryGetCache(assemblyFile, hashFile, configFile, scriptHash, out var config)) + { + // Check for new release only when compiling + Process.Start(new ProcessStartInfo { FileName = Process.GetCurrentProcess().MainModule.FileName, Arguments = Verbs.Update, CreateNoWindow = true, UseShellExecute = false }); + + if (!TryBuild(scriptPath, assemblyFile, hashFile, configFile, scriptHash, buildReferences, out config)) + return ErrorCodes.ScriptCompilationFailed; + } + + var assembly = Assembly.Load(File.ReadAllBytes(assemblyFile)); + var type = assembly.GetType(config.Type); + if (type == null) + throw new Exception($"Entry type '{config.Type}' not found"); + var entryPoint = type.GetMethod(config.Method, BindingFlags.Static | BindingFlags.Public); + if (entryPoint == null) + throw new Exception($"Entry point '{config.Type}.{config.Method}' not found"); + + // Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath); + var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), assemblyLoader } }); + var errorCode = (ErrorCodes?)((await task) as int?) ?? ErrorCodes.OK; + if ((errorCode & ErrorCodes.ErrorMask) != default) + return ErrorCodes.ScriptReturnRangeConflict; + return errorCode; + + static string GetCacheFilenameBase(string filename) + { + using (var hasher = SHA256.Create()) + { + var bytes = hasher.ComputeHash(Encoding.Unicode.GetBytes(filename.ToUpperInvariant())); + var result = new StringBuilder(bytes.Length * 2); + foreach (var b in bytes) + result.Append(b.ToString("X2")); + Directory.CreateDirectory(CachePath); + return Path.Combine(CachePath, result.ToString()); + } + } + + static byte[] GetFileHash(string filename) + { + var bytes = File.ReadAllBytes(filename); + using (var hasher = SHA256.Create()) + { + return hasher.ComputeHash(bytes); + } + } + + static bool TryGetCache(string assemblyFile, string hashFile, string configFile, byte[] scriptHash, out Config config) + { + config = null; + if (!File.Exists(assemblyFile) || !File.Exists(hashFile) || !File.Exists(configFile)) + return false; + + var cachedHash = File.ReadAllBytes(hashFile); + if (!cachedHash.SequenceEqual(scriptHash)) + return false; + + var cfgJson = File.ReadAllText(configFile, Encoding.UTF8); + config = JsonSerializer.Deserialize(cfgJson); + return true; + } + + static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, string configFile, byte[] scriptHash, IEnumerable references, out Config config) + { + config = null; + var lines = File.ReadAllLines(scriptFile); + Console.WriteLine($"Compiling script '{scriptFile}'..."); + var options = ScriptOptions.Default + .WithEmitDebugInformation(true) + .WithFilePath(scriptFile) + .WithFileEncoding(Encoding.UTF8) + .AddReferences(references) + ; + + var script = string.Join(Environment.NewLine, lines); + script = Regex.Replace(script, NuGetReferenceRegex, match => new string(match.Value.Select(x => char.IsWhiteSpace(x) ? x : ' ').ToArray()), RegexOptions.Multiline | RegexOptions.IgnoreCase); + var compilation = CSharpScript.Create(script, options, typeof(ScriptGlobals)).GetCompilation(); + //compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.ConsoleApplication)); + using (var stream = File.OpenWrite(assemblyFile)) + { + var result = compilation.Emit(stream, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded)); + PrintCompilationDiagnostics(result, lines); + if (!result.Success) + return false; + } + + File.WriteAllBytes(hashFile, scriptHash); + + var scriptEntryPoint = compilation.GetEntryPoint(default); + config = new Config + { + Type = scriptEntryPoint.ContainingType.MetadataName, + Method = scriptEntryPoint.Name + }; + + var json = JsonSerializer.Serialize(config); + File.WriteAllText(configFile, json, Encoding.UTF8); + return true; + } + + static async Task<(IEnumerable BuildReferences, InteractiveAssemblyLoader assemblyLoader1)> LoadPackages(string scriptPath) + { + var buildReferences = new HashSet(StringComparer.OrdinalIgnoreCase); + var runtimeReferences = new HashSet(StringComparer.OrdinalIgnoreCase); + var matches = Regex.Matches(File.ReadAllText(scriptPath), NuGetReferenceRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase); + foreach (Match match in matches) + await NuGet.LoadPackage(match.Groups["name"].Value, match.Groups["version"].Value, buildReferences, runtimeReferences); + + var assemblyLoader = new InteractiveAssemblyLoader(); + foreach (var path in runtimeReferences) + assemblyLoader.RegisterDependency(Assembly.LoadFrom(path)); + return (buildReferences, assemblyLoader); + } + + static void PrintCompilationDiagnostics(EmitResult result, string[] lines) + { + var color = Console.ForegroundColor; + foreach (var diag in result.Diagnostics) + { + switch (diag.Severity) + { + case DiagnosticSeverity.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; + case DiagnosticSeverity.Error: Console.ForegroundColor = ConsoleColor.Red; break; + default: Console.ForegroundColor = color; break; + } + + var loc = diag.Location.GetLineSpan(); + Console.WriteLine($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}"); + if (lines != null) + { + var color2 = Console.ForegroundColor; + var codeStart = lines[loc.StartLinePosition.Line].Substring(0, loc.StartLinePosition.Character); + var codeEnd = lines[loc.EndLinePosition.Line].Substring(loc.EndLinePosition.Character); + var code = string.Join(Environment.NewLine, lines.Skip(loc.StartLinePosition.Line).Take(loc.EndLinePosition.Line - loc.StartLinePosition.Line + 1)); + code = code.Substring(codeStart.Length, code.Length - codeStart.Length - codeEnd.Length); + + Console.ForegroundColor = color; + Console.Write(codeStart); + Console.ForegroundColor = color2; + Console.Write(code); + Console.ForegroundColor = color; + Console.Write(codeEnd); + Console.WriteLine(); + } + } + Console.ForegroundColor = color; + } + } + } +} \ No newline at end of file diff --git a/Program.Update.cs b/Program.Update.cs new file mode 100644 index 0000000..b55a362 --- /dev/null +++ b/Program.Update.cs @@ -0,0 +1,127 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace CSharpScriptRunner +{ + static partial class Program + { + static async Task Update() + { + const string UpdateMutexName = "C371A9A2-6CBE-43DE-B834-AC8F73E47705"; + + using var mutex = new Mutex(true, UpdateMutexName); + if (!mutex.WaitOne(0, true)) + { + WriteLine($"{Verbs.Update} command is already running", ConsoleColor.Red); + return; + } + + WriteLine("Checking for new version..."); + + using var httpClient = new HttpClient(); + httpClient.Timeout = Timeout.InfiniteTimeSpan; + httpClient.DefaultRequestHeaders.Accept.Clear(); + httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + httpClient.DefaultRequestHeaders.Add("User-Agent", nameof(CSharpScriptRunner)); + var response = await httpClient.GetAsync(UpdateRequestUri).ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + + var release = JsonSerializer.Deserialize(await response.Content.ReadAsByteArrayAsync()); + var dstDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner), release.Version); + if (release.Version == BuildInfo.ReleaseTag) + { + foreach (var dir in Directory.EnumerateDirectories(Path.GetDirectoryName(dstDir))) + { + if (string.Equals(dir, dstDir, StringComparison.OrdinalIgnoreCase)) + continue; + try { Directory.Delete(dir, true); } + catch { continue; } + } + WriteLine($"${nameof(CSharpScriptRunner)} is up-to-date ({BuildInfo.ReleaseTag})", ConsoleColor.Green); + return; + } + + var tmpDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner), Guid.NewGuid().ToString()); + if (Directory.Exists(dstDir)) + { + WriteLine($"Newest version ({release.Version}) is already isntalled", ConsoleColor.Green); + return; + } + + WriteLine($"New version ({release.Version}) available, downloading..."); + + var platform = BuildInfo.RuntimeIdentifier.Split('-').First(); + var downloadUrl = release.Assets.Select(x => x.DownloadUrl).FirstOrDefault(x => x.EndsWith($"-{platform}.zip", StringComparison.OrdinalIgnoreCase)); + if (downloadUrl == null) + { + WriteLine("Operation failed", ConsoleColor.Red); + return; + } + + httpClient.DefaultRequestHeaders.Accept.Clear(); + response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead); + using (var ms = new MemoryStream((int)response.Content.Headers.ContentLength)) + { + using (var stream = await response.Content.ReadAsStreamAsync()) + { + var buffer = new byte[(int)response.Content.Headers.ContentLength / 100 + 1]; + var progress = string.Empty; + while (true) + { + var length = await stream.ReadAsync(buffer, 0, buffer.Length); + if (length < 1) + break; + await ms.WriteAsync(buffer, 0, length); + var newProgress = $"{(double)ms.Length / ms.Capacity,4:P0}"; + if (newProgress != progress) + { + progress = newProgress; + try { Console.CursorLeft = 0; } + catch { } + Console.Write(progress); + } + } + Console.WriteLine(); + } + + ms.Seek(0, SeekOrigin.Begin); + using (var archive = new ZipArchive(ms, ZipArchiveMode.Read)) + { + await Task.WhenAll(archive.Entries.Select(async entry => + { + Console.WriteLine($"Extracting {entry.FullName} ..."); + var parts = entry.FullName.Split('/'); + parts = parts.Take(1).Append("bin").Concat(parts.Skip(1)).Prepend(tmpDir).ToArray(); + var dstPath = Path.Combine(parts); + Directory.CreateDirectory(Path.GetDirectoryName(dstPath)); + using var src = entry.Open(); + using var dst = new FileStream(dstPath, FileMode.Create); + await src.CopyToAsync(dst); + })); + } + } + + Directory.Move(tmpDir, dstDir); + + var installed = false; + var path = Path.Combine(dstDir, BuildInfo.RuntimeIdentifier.Split('-').Last(), "bin", Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName)); + if (File.Exists(path)) + { + using var process = Process.Start(new ProcessStartInfo { FileName = path, Arguments = "install inplace", UseShellExecute = false }); + process.WaitForExit(); + installed = process.ExitCode == (int)ErrorCodes.OK; + } + + if (!installed) + Directory.Move(dstDir, tmpDir); + } + } +} \ No newline at end of file diff --git a/Program.cs b/Program.cs index edff824..06f7dae 100644 --- a/Program.cs +++ b/Program.cs @@ -10,7 +10,6 @@ using System.Security.Cryptography; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Collections.Concurrent; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis; @@ -19,7 +18,9 @@ using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.CSharp; -using System.Threading; +using System.IO.Compression; +using System.Net.Http; +using System.Net.Http.Headers; namespace CSharpScriptRunner { @@ -30,68 +31,61 @@ public sealed class ScriptGlobals internal ScriptGlobals(string[] args) => Args = args; } - static class Program + static partial class Program { const string CmdAlias = "csx"; static readonly string CachePath = Path.Combine(Path.GetTempPath(), nameof(CSharpScriptRunner)); + const string UpdateRequestUri = "https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest"; + const string PowershellUpdateCommand = + @"$dir=md ""$Env:Temp\{$(New-Guid)}""; $bkp=$ProgressPreference; $ProgressPreference='SilentlyContinue'; Write-Host 'Downloading...'; Invoke-WebRequest (Invoke-RestMethod -Uri '" + UpdateRequestUri + + @"' | select -Expand assets | select-string -InputObject {$_.browser_download_url} -Pattern '-win\.zip$' | Select -Expand Line -First 1) -OutFile ""$dir\CSX.zip""; Write-Host 'Expanding archive...'; Expand-Archive -Path ""$dir\CSX.zip"" -DestinationPath ""$dir""; & ""$dir\win\x64\CSharpScriptRunner.exe"" 'install'; Remove-Item $dir -Recurse; $ProgressPreference=$bkp; Write-Host 'Done'"; + + static class Verbs { public const string Version = "--version"; public const string Install = "install"; + public const string Update = "update"; public const string New = "new"; public const string ClearCache = "clear-cache"; public const string InitVSCode = "init-vscode"; } - sealed class CurrentThreadSynchronizationContext : System.Threading.SynchronizationContext + enum ErrorCodes : uint { - readonly BlockingCollection<(SendOrPostCallback Callback, object State, ManualResetEventSlim Signal)> _queue = new(); - - CurrentThreadSynchronizationContext() { } - - public override void Send(SendOrPostCallback d, object state) - { - var signal = new ManualResetEventSlim(false); - _queue.Add((d, state, signal)); - signal.Wait(); - } - - public override void Post(SendOrPostCallback d, object state) - { - _queue.Add((d, state, null)); - } - - public static void Run(Func main) - { - var syncCtx = new CurrentThreadSynchronizationContext(); - SynchronizationContext.SetSynchronizationContext(syncCtx); - var mainTask = main(); - mainTask.ContinueWith(t => syncCtx._queue.CompleteAdding()); - foreach (var item in syncCtx._queue.GetConsumingEnumerable()) - { - item.Callback(item.State); - item.Signal?.Set(); - } - mainTask.Wait(); - } + OK = 0, + ErrorMask = 0xFF000000, + ScriptReturnRangeConflict = 0x01_00_00_00, + GenericError, + UnrecognizedArgument, + ScriptFileDoesNotExist, + ScriptCompilationFailed, } [STAThread] // Must run on STA thread (for WinForms/WPF support) - static void Main(string[] args) + static int Main(string[] args) { - CurrentThreadSynchronizationContext.Run(() => MainAsync(args)); + return CurrentThreadSynchronizationContext.Run(() => MainAsync(args)); } - static async Task MainAsync(string[] args) + static async Task MainAsync(string[] args) { + using var thisProcess = Process.GetCurrentProcess(); + var dir = Path.Combine(Path.GetDirectoryName(thisProcess.MainModule.FileName), "running"); + Directory.CreateDirectory(dir); + + using var file = new FileStream(Path.Combine(dir, thisProcess.Id.ToString()), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 512, FileOptions.DeleteOnClose | FileOptions.Asynchronous); + using (var writer = new StreamWriter(file, null, -1, true)) + await writer.WriteLineAsync(Environment.CommandLine); + Console.WriteLine($"{nameof(CSharpScriptRunner)}, {BuildInfo.ReleaseTag}"); if (args == null || args.Length == 0) { - await PrintHelp(); - return; + PrintHelp(); + return ErrorCodes.OK; } try @@ -100,10 +94,11 @@ static async Task MainAsync(string[] args) { case Verbs.Version: break; case Verbs.Install: await Install(args.Length > 1 ? string.Equals(args[1], "inplace", StringComparison.OrdinalIgnoreCase) : false); break; + case Verbs.Update: await Update(); break; case Verbs.New: CreateNew(args.Length > 1 ? args[1] : null); break; case Verbs.ClearCache: await ClearCache(); break; case Verbs.InitVSCode: InitVSCode(); break; - default: await RunScript(args); break; + default: return await RunScript(args); } } catch (Exception ex) @@ -111,25 +106,22 @@ static async Task MainAsync(string[] args) if (ex is AggregateException aggregateException) ex = aggregateException.InnerException; WriteLine(ex.ToString(), ConsoleColor.Red); + return ErrorCodes.GenericError; } + return ErrorCodes.OK; } - static async Task PrintHelp() + static void PrintHelp() { - var newRelease = await Updates.CheckForNewRelease(); - if (newRelease != default) - { - Console.WriteLine($"A new release of {nameof(CSharpScriptRunner)} ({newRelease.Version}) is available at {newRelease.Url}"); - Console.WriteLine($"Install with powershell: {Updates.PowershellCommand}"); - } - - var exe = nameof(CSharpScriptRunner); + var exe = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName); Console.WriteLine($"Alias: {CmdAlias}"); Console.WriteLine($"{exe} [-r] ScriptFilePath [args]"); Console.WriteLine($" Executes the specified script."); Console.WriteLine($" : Runtime, e.g. x86/x64"); Console.WriteLine($"{exe} {Verbs.Install}"); Console.WriteLine($" Installs {exe} for the current user."); + Console.WriteLine($"{exe} {Verbs.Update}"); + Console.WriteLine($" Updates {exe} for the current user."); Console.WriteLine($"{exe} {Verbs.New} [template]"); Console.WriteLine($" If a template name is provided, a new script file [template].csx is created."); Console.WriteLine($" If the template name is omitted, the available templates are listed."); @@ -137,424 +129,7 @@ static async Task PrintHelp() Console.WriteLine($" Initializes VS Code debugging support (creates .vscode directory)"); Console.WriteLine($"{exe} {Verbs.ClearCache}"); Console.WriteLine($" Cleares the cache of previously compiled scripts."); - } - - static async Task Install(bool installInPlace) - { - var oldPath = Process.GetCurrentProcess().MainModule.FileName; - var newPath = oldPath; - var filename = Path.GetFileName(oldPath); - var oldDir = Path.GetDirectoryName(oldPath); - var runtimeDir = Path.GetFileName(oldDir); - oldDir = Path.GetDirectoryName(oldDir); - if (installInPlace) - { - foreach (var file in Directory.EnumerateFiles(oldDir, filename, SearchOption.AllDirectories)) - File.Copy(file, Path.Combine(Path.GetDirectoryName(file), CmdAlias + Path.GetExtension(filename)), true); - } - else - { - var newDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner)); - newPath = Path.Combine(newDir, runtimeDir, "bin", filename); - if (Directory.Exists(newDir)) - { - WriteLine($"Removing previous installation..."); - try - { - if (File.Exists(newPath)) - File.Delete(newPath); - Directory.Delete(newDir, true); - } - catch (Exception ex) - { - WriteLine($"Operation failed with {ex.GetType().Name}: {ex.Message}", ConsoleColor.Red); - Console.WriteLine(); - var count = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length - 1; - WriteLine($"Please close all running instances ({count}) and try again:", ConsoleColor.Red); - return; - } - } - Directory.CreateDirectory(newDir); - - foreach (var dir in Directory.EnumerateDirectories(oldDir)) - { - if (!File.Exists(Path.Combine(dir, filename))) - continue; - - var dstDir = Path.Combine(newDir, Path.GetFileName(dir)); - await Task.WhenAll(Directory.EnumerateFiles(dir, "*", new EnumerationOptions { RecurseSubdirectories = true }).Select(file => Task.Run(() => - { - var dst = Path.Combine(dstDir, "bin", file.Substring(dir.Length + 1)); - Directory.CreateDirectory(Path.GetDirectoryName(dst)); - Console.WriteLine($"Copying {dst} ..."); - File.Copy(file, dst, true); - }))); - - File.WriteAllText(Path.Combine(dstDir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*"); - File.WriteAllText(Path.Combine(dstDir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*"); - } - } - - var envPath = (Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User) - ?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) - .Where(x => !x.Contains(nameof(CSharpScriptRunner))) ?? Array.Empty()) - .Append(Path.GetDirectoryName(Path.GetDirectoryName(newPath))); - Environment.SetEnvironmentVariable("Path", string.Join(';', envPath), EnvironmentVariableTarget.User); - Environment.SetEnvironmentVariable(nameof(CSharpScriptRunner) + "RuntimesDir", Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(newPath))), EnvironmentVariableTarget.User); - - var filetype = ".csx"; - - // https://docs.microsoft.com/en-us/windows/win32/shell/context-menu-handlers - using (var regKeyExt = Registry.CurrentUser.CreateSubKey($@"Software\Classes\{filetype}", true)) - { - var tmp = regKeyExt.GetValue(string.Empty) as string; - if (!string.IsNullOrEmpty(tmp)) - filetype = tmp; - else - { - filetype = filetype.Substring(1) + "_auto_file"; - regKeyExt.SetValue(string.Empty, filetype); - } - } - - using (var regKey = Registry.CurrentUser.CreateSubKey($@"Software\Classes\{filetype}\shell\execute", true)) - using (var regKeyCommand = regKey.CreateSubKey("command", true)) - { - regKey.SetValue(string.Empty, "C# Skript ausführen"); - regKeyCommand.SetValue(string.Empty, $"\"{newPath}\" \"%1\""); - } - - using (var regKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Classes\*\shell\CSharpScriptRunner", true)) - using (var regKeyCommand = regKey.CreateSubKey("command", true)) - { - regKey.SetValue(string.Empty, "C# Skript ausführen"); - regKey.SetValue("AppliesTo", "System.FileExtension:\"csx\"", RegistryValueKind.String); - regKey.SetValue("Position", "Top", RegistryValueKind.String); - regKeyCommand.SetValue(string.Empty, $"\"{newPath}\" \"%1\""); - } - - WriteLine("Installation was successful.", ConsoleColor.Green); - await ClearCache(); - } - - static string GetCacheFilenameBase(string filename) - { - using (var hasher = SHA256.Create()) - { - var bytes = hasher.ComputeHash(Encoding.Unicode.GetBytes(filename.ToUpperInvariant())); - var result = new StringBuilder(bytes.Length * 2); - foreach (var b in bytes) - result.Append(b.ToString("X2")); - Directory.CreateDirectory(CachePath); - return Path.Combine(CachePath, result.ToString()); - } - } - - static byte[] GetFileHash(string filename) - { - var bytes = File.ReadAllBytes(filename); - using (var hasher = SHA256.Create()) - { - return hasher.ComputeHash(bytes); - } - } - - sealed class Config - { - public string Type { get; set; } - public string Method { get; set; } - } - - static bool TryGetCache(string assemblyFile, string hashFile, string configFile, byte[] scriptHash, out Config config) - { - config = null; - if (!File.Exists(assemblyFile) || !File.Exists(hashFile) || !File.Exists(configFile)) - return false; - - var cachedHash = File.ReadAllBytes(hashFile); - if (!cachedHash.SequenceEqual(scriptHash)) - return false; - - var cfgJson = File.ReadAllText(configFile, Encoding.UTF8); - config = JsonSerializer.Deserialize(cfgJson); - return true; - } - - const string NuGetReferenceRegex = @"^\s*#r\s+""\s*nuget:\s*(?[\w\d.-]+)\s*\/\s*(?[\w\d.-]+)\s*""\s*$"; - - static bool TryBuild(string scriptFile, string assemblyFile, string hashFile, string configFile, byte[] scriptHash, IEnumerable references, out Config config) - { - config = null; - var lines = File.ReadAllLines(scriptFile); - Console.WriteLine($"Compiling script '{scriptFile}'..."); - var options = ScriptOptions.Default - .WithEmitDebugInformation(true) - .WithFilePath(scriptFile) - .WithFileEncoding(Encoding.UTF8) - .AddReferences(references) - ; - - var script = string.Join(Environment.NewLine, lines); - script = Regex.Replace(script, NuGetReferenceRegex, match => new string(match.Value.Select(x => char.IsWhiteSpace(x) ? x : ' ').ToArray()), RegexOptions.Multiline | RegexOptions.IgnoreCase); - var compilation = CSharpScript.Create(script, options, typeof(ScriptGlobals)).GetCompilation(); - //compilation = compilation.WithOptions(compilation.Options.WithOutputKind(OutputKind.ConsoleApplication)); - using (var stream = File.OpenWrite(assemblyFile)) - { - var result = compilation.Emit(stream, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded)); - PrintCompilationDiagnostics(result, lines); - if (!result.Success) - return false; - } - - File.WriteAllBytes(hashFile, scriptHash); - - var scriptEntryPoint = compilation.GetEntryPoint(default); - config = new Config - { - Type = scriptEntryPoint.ContainingType.MetadataName, - Method = scriptEntryPoint.Name - }; - - var json = JsonSerializer.Serialize(config); - File.WriteAllText(configFile, json, Encoding.UTF8); - return true; - } - - static async Task<(IEnumerable BuildReferences, InteractiveAssemblyLoader assemblyLoader1)> LoadPackages(string scriptPath) - { - var buildReferences = new HashSet(StringComparer.OrdinalIgnoreCase); - var runtimeReferences = new HashSet(StringComparer.OrdinalIgnoreCase); - var matches = Regex.Matches(File.ReadAllText(scriptPath), NuGetReferenceRegex, RegexOptions.Multiline | RegexOptions.IgnoreCase); - foreach (Match match in matches) - await NuGet.LoadPackage(match.Groups["name"].Value, match.Groups["version"].Value, buildReferences, runtimeReferences); - - var assemblyLoader = new InteractiveAssemblyLoader(); - foreach (var path in runtimeReferences) - assemblyLoader.RegisterDependency(Assembly.LoadFrom(path)); - return (buildReferences, assemblyLoader); - } - - - static async Task RunScript(string[] arguments) - { - IEnumerable args = arguments; - var runtimeExt = string.Empty; - while (args.FirstOrDefault()?.StartsWith('-') ?? false) - { - var arg = args.First(); - args = args.Skip(1); - if (arg.StartsWith("-r", StringComparison.OrdinalIgnoreCase)) - runtimeExt = arg.Substring(2); - else - { - WriteLine($"Argument {arg} is not recognized.", ConsoleColor.Red); - return; - } - } - - var filePath = args.FirstOrDefault(); - if (!File.Exists(filePath)) - { - WriteLine($"Script file '{filePath}' does not exist.", ConsoleColor.Red); - return; - } - - var scriptPath = Path.GetFullPath(filePath); - if (string.IsNullOrEmpty(runtimeExt)) - runtimeExt = Path.GetExtension(Path.GetFileNameWithoutExtension(scriptPath)).TrimStart('.'); - if (!string.IsNullOrEmpty(runtimeExt)) - { - var exePath = Process.GetCurrentProcess().MainModule.FileName; - var filename = Path.GetFileName(exePath); - var dir = Path.GetDirectoryName(Path.GetDirectoryName(exePath)); - var runtimeDir = Path.GetFileName(dir); - dir = Path.GetDirectoryName(dir); - if (runtimeExt != runtimeDir) - { - exePath = Path.Combine(dir, runtimeExt, "bin", filename); - if (File.Exists(exePath)) - { - Process.Start(new ProcessStartInfo(exePath, string.Join(" ", args.Select(x => $"\"{x.Replace("\"", "\\\"")}\""))) { UseShellExecute = false }).WaitForExit(); - return; - } - - WriteLine($"Warning: Runtime '{runtimeExt}' was not found. Proceeding anyway...", ConsoleColor.Yellow); - } - } - - var (buildReferences, assemblyLoader) = await LoadPackages(scriptPath); - - var cacheFileBase = GetCacheFilenameBase(scriptPath); - var assemblyFile = cacheFileBase + ".dll"; - var hashFile = cacheFileBase + ".hash"; - var configFile = cacheFileBase + ".json"; - var scriptHash = GetFileHash(scriptPath); - - if (!TryGetCache(assemblyFile, hashFile, configFile, scriptHash, out var config)) - { - // Check for new release only when compiling - var newRelease = await Updates.CheckForNewRelease(); - if (newRelease != default) - { - Console.WriteLine($"A new release of {nameof(CSharpScriptRunner)} ({newRelease.Version}) is available at {newRelease.Url}"); - Console.WriteLine($"Install with powershell: {Updates.PowershellCommand}"); - } - - if (!TryBuild(scriptPath, assemblyFile, hashFile, configFile, scriptHash, buildReferences, out config)) - return; - } - - var assembly = Assembly.Load(File.ReadAllBytes(assemblyFile)); - var type = assembly.GetType(config.Type); - if (type == null) - return; - var entryPoint = type.GetMethod(config.Method, BindingFlags.Static | BindingFlags.Public); - if (entryPoint == null) - return; - - // Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath); - var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), assemblyLoader } }); - await task; - } - - static void PrintCompilationDiagnostics(EmitResult result, string[] lines) - { - var color = Console.ForegroundColor; - foreach (var diag in result.Diagnostics) - { - switch (diag.Severity) - { - case DiagnosticSeverity.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; - case DiagnosticSeverity.Error: Console.ForegroundColor = ConsoleColor.Red; break; - default: Console.ForegroundColor = color; break; - } - - var loc = diag.Location.GetLineSpan(); - Console.WriteLine($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}"); - if (lines != null) - { - var color2 = Console.ForegroundColor; - var codeStart = lines[loc.StartLinePosition.Line].Substring(0, loc.StartLinePosition.Character); - var codeEnd = lines[loc.EndLinePosition.Line].Substring(loc.EndLinePosition.Character); - var code = string.Join(Environment.NewLine, lines.Skip(loc.StartLinePosition.Line).Take(loc.EndLinePosition.Line - loc.StartLinePosition.Line + 1)); - code = code.Substring(codeStart.Length, code.Length - codeStart.Length - codeEnd.Length); - - Console.ForegroundColor = color; - Console.Write(codeStart); - Console.ForegroundColor = color2; - Console.Write(code); - Console.ForegroundColor = color; - Console.Write(codeEnd); - Console.WriteLine(); - } - } - Console.ForegroundColor = color; - } - - static void CreateNew(string template) - { - // Script method: - // public static bool ExitAndUpdateEngine() - // { - // var count = System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length - 1; - // if (count > 0) - // { - // Script.WriteLines(new[] { - // "The script engine cannot be updated, while there are running script instances.", - // $"There are currently {count} running script instances." }, ConsoleColor.Yellow); - // return false; - // } - // var cmd = "{PowershellCommandEscaped}".Replace("\"", "\\\""); - // System.Diagnostics.Process.Start(new ProcessStartInfo { FileName = "powershell", Arguments = $"-NoExit -Command \"{cmd}\"", UseShellExecute = true }); - // Environment.Exit(0); - // return true; - // } - - var templates = typeof(Program).Assembly.GetManifestResourceNames() - .Where(x => string.Equals(Path.GetExtension(x), ".csx", StringComparison.OrdinalIgnoreCase)) - .ToDictionary(x => Path.GetExtension(Path.GetFileNameWithoutExtension(x)).Substring(1), StringComparer.OrdinalIgnoreCase); - - if (template == null) - { - Console.Write("Available templates: "); - Console.WriteLine(string.Join(", ", templates.Keys)); - Console.Write("Enter the name of the template you wish to create: "); - template = Console.ReadLine().Trim(); - } - - if (!templates.TryGetValue(template, out var resName)) - { - WriteLine($"The template '{template}' does not exists.", ConsoleColor.Red); - return; - } - - var filename = template + ".csx"; - if (File.Exists(filename)) - { - WriteLine($"The file '{filename} already exists.", ConsoleColor.Red); - return; - } - - using (var res = new StreamReader(typeof(Program).Assembly.GetManifestResourceStream(resName))) - using (var file = new StreamWriter(File.OpenWrite(filename), Encoding.UTF8)) - { - var text = res.ReadToEnd(); - text = text - .Replace("{PowershellCommand}", Updates.PowershellCommand) - .Replace("{PowershellCommandEscaped}", Updates.PowershellCommand.Replace("\\", "\\\\").Replace("\"", "\\\"")); - file.Write(text); - } - - WriteLine($"The file '{filename}' was created.", ConsoleColor.Green); - } - - static async Task ClearCache() - { - if (!Directory.Exists(CachePath)) - return; - - await Task.WhenAll(Directory.EnumerateFiles(CachePath).Select(path => Task.Run(() => - { - try { File.Delete(path); } - catch (IOException) { } - catch (UnauthorizedAccessException) { } - }))); - WriteLine("Cache cleared", ConsoleColor.Green); - } - - static void InitVSCode() - { - const string VSCodeDir = ".vscode"; - const string Filter = ".Templates.vscode."; - - var templates = typeof(Program).Assembly.GetManifestResourceNames() - .Select(x => (i: x.IndexOf(Filter), s: x)) - .Where(x => x.i > -1) - .Select(x => (name: x.s, File: Path.Combine(VSCodeDir, x.s.Substring(x.i + Filter.Length)))); - - var dir = new DirectoryInfo(VSCodeDir); - if (!dir.Exists) - { - dir.Create(); - //dir.Attributes |= FileAttributes.Hidden; - } - - foreach (var template in templates) - { - if (File.Exists(template.File)) - { - WriteLine($"File '{template.File}' already exists.", ConsoleColor.Yellow); - continue; - } - - using (var stream = typeof(Program).Assembly.GetManifestResourceStream(template.name)) - using (var file = File.OpenWrite(template.File)) - { - WriteLine($"Creating file '{template.File}'...", ConsoleColor.Green); - stream.CopyTo(file); - } - } - } + } static void WriteLine(string line, ConsoleColor color = (ConsoleColor)(-1)) { diff --git a/Templates/Script.csx b/Templates/Script.csx index eff273d..055d0c3 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -34,12 +34,13 @@ return 0; // End of script #region Utilities -public static class Script +static class Script { static string GetScriptPath([System.Runtime.CompilerServices.CallerFilePath] string path = null) => path; public static string ScriptPath { get; } = GetScriptPath(); public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath); public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath); + public static string EngineAlias { get; } = System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index 683b3c4..aa5b1f8 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -58,82 +58,82 @@ return 0; // End of script #region Utilities -public static class Script +static class Script { - static string GetScriptPath([System.Runtime.CompilerServices.CallerFilePath] string path = null) => path; - public static string ScriptPath { get; } = GetScriptPath(); - public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath); - public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath); + static string GetScriptPath([System.Runtime.CompilerServices.CallerFilePath] string path = null) => path; + public static string ScriptPath { get; } = GetScriptPath(); + public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath); + public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath); + public static string EngineAlias { get; } = System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); - static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; + static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; - [System.Runtime.InteropServices.DllImport("user32.dll")] - static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); - const int SW_HIDE = 0; - const int SW_SHOW = 5; + const int SW_HIDE = 0; + const int SW_SHOW = 5; - public static void HideConsole() { IsConsoleHidden = true; ShowWindow(_consoleWindow, SW_HIDE); } - public static void ShowConsole() { IsConsoleHidden = false; ShowWindow(_consoleWindow, SW_SHOW); } - public static bool IsConsoleHidden { get; private set; } = false; + public static void HideConsole() { IsConsoleHidden = true; ShowWindow(_consoleWindow, SW_HIDE); } + public static void ShowConsole() { IsConsoleHidden = false; ShowWindow(_consoleWindow, SW_SHOW); } + public static bool IsConsoleHidden { get; private set; } = false; - public static void WriteLine(string text, ConsoleColor color = (ConsoleColor)(-1)) - { - var c = Console.ForegroundColor; - if ((int)color > -1) - Console.ForegroundColor = color; - Console.WriteLine(text); - Console.ForegroundColor = c; - } - - public static void WriteLines(IEnumerable lines, ConsoleColor color = (ConsoleColor)(-1)) + static readonly object _lock = new(); + static void DoWrite(ConsoleColor color, Action action) { - var c = Console.ForegroundColor; - if ((int)color > -1) + if ((int)color == -1) + { + action(); + return; + } + + lock (_lock) + { + var c = Console.ForegroundColor; Console.ForegroundColor = color; - foreach (var line in lines) - Console.WriteLine(line); - Console.ForegroundColor = c; + action(); + Console.ForegroundColor = c; + } } + public static void WriteLine(string text, ConsoleColor color = (ConsoleColor)(-1)) + => DoWrite(color, () => Console.WriteLine(text)); + + public static void WriteLines(IEnumerable lines, ConsoleColor color = (ConsoleColor)(-1)) + => DoWrite(color, () => { foreach (var line in lines) Console.WriteLine(line); }); + public static void Write(string text, ConsoleColor color = (ConsoleColor)(-1)) - { - var c = Console.ForegroundColor; - if ((int)color > -1) - Console.ForegroundColor = color; - Console.Write(text); - Console.ForegroundColor = c; - } + => DoWrite(color, () => Console.Write(text)); - public static IDictionary ParseArguments(IEnumerable args) - { - var arguments = new Dictionary(StringComparer.OrdinalIgnoreCase); - string key = null; - foreach (var value in args) - { - if (value.StartsWith("-")) - { - if (key != null) - arguments[key] = true.ToString(); - key = value.Substring(1); - } - else - { - if (key == null) - throw new ArgumentNullException(value, "The parameter is missing its name."); - arguments[key] = value; - key = null; - } - } - if (key != null) - arguments[key] = true.ToString(); - return arguments; - } + public static IDictionary ParseArguments(IEnumerable args) + { + var arguments = new Dictionary(StringComparer.OrdinalIgnoreCase); + string key = null; + foreach (var value in args) + { + if (value.StartsWith("-")) + { + if (key != null) + arguments[key] = true.ToString(); + key = value.Substring(1); + } + else + { + if (key == null) + throw new ArgumentNullException(value, "The parameter is missing its name."); + arguments[key] = value; + key = null; + } + } + if (key != null) + arguments[key] = true.ToString(); + return arguments; + } } #region WPF utility classes -public abstract class NotifyPropertyChanged : INotifyPropertyChanged +abstract class NotifyPropertyChanged : INotifyPropertyChanged { string[] _propertyNames; @@ -189,13 +189,13 @@ public abstract class NotifyPropertyChanged : INotifyPropertyChanged } } -public sealed class Command : Command +sealed class Command : Command { public Command(Action execute, Func queryCanExecute = null) : base(par => execute(), queryCanExecute == null ? null : new Func(ignored => queryCanExecute())) { } } -public class Command : NotifyPropertyChanged, ICommand +class Command : NotifyPropertyChanged, ICommand { readonly Action _execute; readonly Func _queryCanExecute; @@ -252,7 +252,7 @@ public class Command : NotifyPropertyChanged, ICommand } } -public sealed class AsyncCommand : AsyncCommand +sealed class AsyncCommand : AsyncCommand { public AsyncCommand(Func execute, Func queryCanExecute = null) : base((par, token) => execute(token), queryCanExecute == null ? null : new Func(ignored => queryCanExecute())) { } @@ -261,7 +261,7 @@ public sealed class AsyncCommand : AsyncCommand : base((par, token) => execute(), queryCanExecute == null ? null : new Func(ignored => queryCanExecute())) { } } -public class AsyncCommand : NotifyPropertyChanged, ICommand +class AsyncCommand : NotifyPropertyChanged, ICommand { readonly Func _execute; readonly Func _queryCanExecute; diff --git a/Updates.cs b/Updates.cs index 44a4d88..69fcd95 100644 --- a/Updates.cs +++ b/Updates.cs @@ -15,39 +15,48 @@ sealed class ReleaseInfo [JsonPropertyName("html_url")] public string Url { get; set; } - } - static class Updates - { - const string RequestUri = "https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest"; - public const string PowershellCommand = - @"$dir=md ""$Env:Temp\{$(New-Guid)}""; $bkp=$ProgressPreference; $ProgressPreference='SilentlyContinue'; Write-Host 'Downloading...'; Invoke-WebRequest (Invoke-RestMethod -Uri '" + RequestUri + - @"' | select -Expand assets | select-string -InputObject {$_.browser_download_url} -Pattern '-win\.zip$' | Select -Expand Line -First 1) -OutFile ""$dir\CSX.zip""; Write-Host 'Expanding archive...'; Expand-Archive -Path ""$dir\CSX.zip"" -DestinationPath ""$dir""; & ""$dir\win\x64\CSharpScriptRunner.exe"" 'install'; Remove-Item $dir -Recurse; $ProgressPreference=$bkp; Write-Host 'Done'"; - - public static async Task CheckForNewRelease() + [JsonPropertyName("assets")] + public List Assets { get; set; } + + public sealed class Asset { - if (!BuildInfo.ReleaseTag.StartsWith('v') || !Version.TryParse(BuildInfo.ReleaseTag.Substring(1), out var version)) - return default; - - using (var httpClient = new HttpClient()) - { - httpClient.DefaultRequestHeaders.Accept.Clear(); - httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - httpClient.DefaultRequestHeaders.Add("User-Agent", "CSharpScriptRunner"); - HttpResponseMessage response; - try { response = await httpClient.GetAsync(RequestUri); } - catch { return default; } - if (!response.IsSuccessStatusCode) - return default; - - var release = JsonSerializer.Deserialize(await response.Content.ReadAsByteArrayAsync()); - if (string.IsNullOrEmpty(release.Version) || string.IsNullOrEmpty(release.Url) || !release.Version.StartsWith('v') || !Version.TryParse(release.Version.Substring(1), out var releaseVersion)) - return default; - - if (version < releaseVersion) - return release; - } - return default; + [JsonPropertyName("browser_download_url")] + public string DownloadUrl { get; set; } } } + + // static class Updates + // { + // const string RequestUri = "https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest"; + // public const string PowershellCommand = + // @"$dir=md ""$Env:Temp\{$(New-Guid)}""; $bkp=$ProgressPreference; $ProgressPreference='SilentlyContinue'; Write-Host 'Downloading...'; Invoke-WebRequest (Invoke-RestMethod -Uri '" + RequestUri + + // @"' | select -Expand assets | select-string -InputObject {$_.browser_download_url} -Pattern '-win\.zip$' | Select -Expand Line -First 1) -OutFile ""$dir\CSX.zip""; Write-Host 'Expanding archive...'; Expand-Archive -Path ""$dir\CSX.zip"" -DestinationPath ""$dir""; & ""$dir\win\x64\CSharpScriptRunner.exe"" 'install'; Remove-Item $dir -Recurse; $ProgressPreference=$bkp; Write-Host 'Done'"; + + // public static async Task CheckForNewRelease() + // { + // // if (!BuildInfo.ReleaseTag.StartsWith('v') || !Version.TryParse(BuildInfo.ReleaseTag.Substring(1), out var version)) + // // return default; + + // using (var httpClient = new HttpClient()) + // { + // httpClient.DefaultRequestHeaders.Accept.Clear(); + // httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + // httpClient.DefaultRequestHeaders.Add("User-Agent", "CSharpScriptRunner"); + // HttpResponseMessage response; + // try { response = await httpClient.GetAsync(RequestUri); } + // catch { return default; } + // if (!response.IsSuccessStatusCode) + // return default; + + // var release = JsonSerializer.Deserialize(await response.Content.ReadAsByteArrayAsync()); + // if (string.IsNullOrEmpty(release.Version) || string.IsNullOrEmpty(release.Url) || !release.Version.StartsWith('v') || !Version.TryParse(release.Version.Substring(1), out var releaseVersion)) + // return default; + + // // if (version < releaseVersion) + // return release; + // } + // return default; + // } + // } } \ No newline at end of file From c235d218d45482490d6128f2fca16404e36ca091 Mon Sep 17 00:00:00 2001 From: developer Date: Wed, 28 Apr 2021 08:12:34 +0200 Subject: [PATCH 31/43] list-running command --- CSharpScriptRunner.csproj | 13 ++++---- Program.Install.cs | 57 +++++++++++++++++++++++------------ Program.RunScript.cs | 4 +-- Program.Update.cs | 24 +++++++++++++-- Program.cs | 53 +++++++++++++++++++++++++++++---- Templates/Script.csx | 2 ++ Templates/ScriptUI.csx | 1 + Updates.cs | 62 --------------------------------------- publish.ps1 | 2 +- 9 files changed, 121 insertions(+), 97 deletions(-) delete mode 100644 Updates.cs diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index 539d4c6..eefb983 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -8,6 +8,7 @@ true true dev + bin/x64/bin @@ -15,13 +16,13 @@ - + - - - - - + + + + + diff --git a/Program.Install.cs b/Program.Install.cs index 7135c90..befcbbd 100644 --- a/Program.Install.cs +++ b/Program.Install.cs @@ -11,17 +11,31 @@ static partial class Program { static async Task Install(bool installInPlace) { - var oldPath = Process.GetCurrentProcess().MainModule.FileName; - var newPath = oldPath; - var filename = Path.GetFileName(oldPath); - var oldDir = Path.GetDirectoryName(oldPath); - var runtimeDir = Path.GetFileName(oldDir); - oldDir = Path.GetDirectoryName(oldDir); - var newDir = oldDir; + var thisPath = Process.GetCurrentProcess().MainModule.FileName; + var newPath = thisPath; + var filename = Path.GetFileName(thisPath); + var valid = false; - if (!installInPlace) + if (installInPlace) { - newDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner), BuildInfo.ReleaseTag); + var runtimesDir = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(thisPath))); + foreach (var dir in Directory.EnumerateDirectories(runtimesDir)) + { + if (!File.Exists(Path.Combine(dir, "bin", filename))) + continue; + + valid = true; + + File.WriteAllText(Path.Combine(dir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*"); + File.WriteAllText(Path.Combine(dir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*"); + } + } + else + { + var oldDir = Path.GetDirectoryName(thisPath); + var runtimeDir = Path.GetFileName(oldDir); + oldDir = Path.GetDirectoryName(oldDir); + var newDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner), BuildInfo.ReleaseTag); newPath = Path.Combine(newDir, runtimeDir, "bin", filename); if (Directory.Exists(newDir)) { @@ -42,16 +56,15 @@ static async Task Install(bool installInPlace) } } Directory.CreateDirectory(newDir); - } - foreach (var dir in Directory.EnumerateDirectories(oldDir)) - { - if (!File.Exists(Path.Combine(dir, filename))) - continue; - - var dstDir = Path.Combine(newDir, Path.GetFileName(dir)); - if (!installInPlace) + foreach (var dir in Directory.EnumerateDirectories(oldDir)) { + if (!File.Exists(Path.Combine(dir, filename))) + continue; + + valid = true; + + var dstDir = Path.Combine(newDir, Path.GetFileName(dir)); await Task.WhenAll(Directory.EnumerateFiles(dir, "*", new EnumerationOptions { RecurseSubdirectories = true }).Select(file => Task.Run(() => { var dst = Path.Combine(dstDir, "bin", file.Substring(dir.Length + 1)); @@ -59,10 +72,16 @@ static async Task Install(bool installInPlace) Console.WriteLine($"Copying {dst} ..."); File.Copy(file, dst, true); }))); + + File.WriteAllText(Path.Combine(dstDir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*"); + File.WriteAllText(Path.Combine(dstDir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*"); } + } - File.WriteAllText(Path.Combine(dstDir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*"); - File.WriteAllText(Path.Combine(dstDir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*"); + if (!valid) + { + WriteLine("Installation failed", ConsoleColor.Red); + return; } var envPath = (Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User) diff --git a/Program.RunScript.cs b/Program.RunScript.cs index 3a0d962..a8f3c58 100644 --- a/Program.RunScript.cs +++ b/Program.RunScript.cs @@ -28,7 +28,7 @@ sealed class Config static async Task RunScript(string[] arguments) { const string NuGetReferenceRegex = @"^\s*#r\s+""\s*nuget:\s*(?[\w\d.-]+)\s*\/\s*(?[\w\d.-]+)\s*""\s*$"; - + IEnumerable args = arguments; var runtimeExt = string.Empty; while (args.FirstOrDefault()?.StartsWith('-') ?? false) @@ -103,7 +103,7 @@ static async Task RunScript(string[] arguments) // Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath); var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), assemblyLoader } }); var errorCode = (ErrorCodes?)((await task) as int?) ?? ErrorCodes.OK; - if ((errorCode & ErrorCodes.ErrorMask) != default) + if (errorCode > ErrorCodes.OK && errorCode <= ErrorCodes.Reserved) return ErrorCodes.ScriptReturnRangeConflict; return errorCode; diff --git a/Program.Update.cs b/Program.Update.cs index b55a362..83396bd 100644 --- a/Program.Update.cs +++ b/Program.Update.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; @@ -6,6 +7,7 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Text.Json; +using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; @@ -13,6 +15,24 @@ namespace CSharpScriptRunner { static partial class Program { + sealed class ReleaseInfo + { + [JsonPropertyName("tag_name")] + public string Version { get; set; } + + [JsonPropertyName("html_url")] + public string Url { get; set; } + + [JsonPropertyName("assets")] + public List Assets { get; set; } + + public sealed class Asset + { + [JsonPropertyName("browser_download_url")] + public string DownloadUrl { get; set; } + } + } + static async Task Update() { const string UpdateMutexName = "C371A9A2-6CBE-43DE-B834-AC8F73E47705"; @@ -95,7 +115,7 @@ static async Task Update() ms.Seek(0, SeekOrigin.Begin); using (var archive = new ZipArchive(ms, ZipArchiveMode.Read)) { - await Task.WhenAll(archive.Entries.Select(async entry => + foreach (var entry in archive.Entries) { Console.WriteLine($"Extracting {entry.FullName} ..."); var parts = entry.FullName.Split('/'); @@ -105,7 +125,7 @@ await Task.WhenAll(archive.Entries.Select(async entry => using var src = entry.Open(); using var dst = new FileStream(dstPath, FileMode.Create); await src.CopyToAsync(dst); - })); + } } } diff --git a/Program.cs b/Program.cs index 06f7dae..d826455 100644 --- a/Program.cs +++ b/Program.cs @@ -50,17 +50,18 @@ static class Verbs public const string New = "new"; public const string ClearCache = "clear-cache"; public const string InitVSCode = "init-vscode"; + public const string ListRunning = "list-running"; } - enum ErrorCodes : uint + enum ErrorCodes { OK = 0, - ErrorMask = 0xFF000000, - ScriptReturnRangeConflict = 0x01_00_00_00, GenericError, + ScriptReturnRangeConflict, UnrecognizedArgument, ScriptFileDoesNotExist, ScriptCompilationFailed, + Reserved = 0xFF } [STAThread] @@ -76,7 +77,7 @@ static async Task MainAsync(string[] args) var dir = Path.Combine(Path.GetDirectoryName(thisProcess.MainModule.FileName), "running"); Directory.CreateDirectory(dir); - using var file = new FileStream(Path.Combine(dir, thisProcess.Id.ToString()), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 512, FileOptions.DeleteOnClose | FileOptions.Asynchronous); + using var file = new FileStream(Path.Combine(dir, thisProcess.Id.ToString()), FileMode.Create, FileAccess.Write, FileShare.Read, 512, FileOptions.DeleteOnClose | FileOptions.Asynchronous); using (var writer = new StreamWriter(file, null, -1, true)) await writer.WriteLineAsync(Environment.CommandLine); @@ -98,6 +99,7 @@ static async Task MainAsync(string[] args) case Verbs.New: CreateNew(args.Length > 1 ? args[1] : null); break; case Verbs.ClearCache: await ClearCache(); break; case Verbs.InitVSCode: InitVSCode(); break; + case Verbs.ListRunning: await ListRunning(); break; default: return await RunScript(args); } } @@ -129,7 +131,15 @@ static void PrintHelp() Console.WriteLine($" Initializes VS Code debugging support (creates .vscode directory)"); Console.WriteLine($"{exe} {Verbs.ClearCache}"); Console.WriteLine($" Cleares the cache of previously compiled scripts."); - } + Console.WriteLine($"{exe} {Verbs.ListRunning}"); + Console.WriteLine($" Lists the currently running script engine instances."); + Console.WriteLine($"Returned error codes:"); + foreach (var code in Enum.GetValues().Where(x => x != ErrorCodes.Reserved)) + Console.WriteLine($" - {code,3:D} {code}"); + Console.WriteLine($" - Value returned by script."); + Console.WriteLine($" Values {ErrorCodes.OK + 1:D} - {ErrorCodes.Reserved:D} are reserved by the engine."); + Console.WriteLine($" If a script returns a value in the reserved range, {ErrorCodes.ScriptReturnRangeConflict} will be returned instead."); + } static void WriteLine(string line, ConsoleColor color = (ConsoleColor)(-1)) { @@ -138,5 +148,38 @@ static void WriteLine(string line, ConsoleColor color = (ConsoleColor)(-1)) Console.WriteLine(line); Console.ResetColor(); } + + static async Task ListRunning() + { + WriteLine("Process ID RT Arguments"); + WriteLine("---------- --- ---------"); + using var thisProcess = Process.GetCurrentProcess(); + var runtimesDir = Path.GetDirectoryName(thisProcess.MainModule.FileName); // bin + runtimesDir = Path.GetDirectoryName(runtimesDir); // x64 + runtimesDir = Path.GetDirectoryName(runtimesDir); // vX.Y.Z + foreach (var runtimeDir in Directory.EnumerateDirectories(runtimesDir)) + { + var dir = Path.Combine(runtimeDir, "bin", "running"); + if (!Directory.Exists(dir)) + continue; + + var rt = Path.GetFileName(runtimeDir); + + foreach (var file in Directory.EnumerateFiles(dir)) + { + var processId = Path.GetFileNameWithoutExtension(file); + if (thisProcess.Id == int.Parse(processId)) + continue; + + using var reader = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)); + var args = await reader.ReadToEndAsync().ConfigureAwait(false); + if (args.StartsWith('"')) + args = args.Substring(args.IndexOf('"', 1) + 1).TrimStart(); + else + args = args.Split(' ', 2).Last(); + WriteLine($"{processId,10} {rt,-3} {args}"); + } + } + } } } diff --git a/Templates/Script.csx b/Templates/Script.csx index 055d0c3..5f8620a 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -40,7 +40,9 @@ static class Script public static string ScriptPath { get; } = GetScriptPath(); public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath); public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath); + public static string EngineAlias { get; } = System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); + public static string EnginePath { get; } = "%CSharpScriptRunnerRuntimesDir%" + System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Substring(Environment.GetEnvironmentVariable("CSharpScriptRunnerRuntimesDir").Length); static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index aa5b1f8..b4c8ff2 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -65,6 +65,7 @@ static class Script public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath); public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath); public static string EngineAlias { get; } = System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); + public static string EnginePath { get; } = "%CSharpScriptRunnerRuntimesDir%" + System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Substring(Environment.GetEnvironmentVariable("CSharpScriptRunnerRuntimesDir").Length); static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; diff --git a/Updates.cs b/Updates.cs deleted file mode 100644 index 69fcd95..0000000 --- a/Updates.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Net.Http; -using System.Net.Http.Headers; -using System.Threading.Tasks; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Collections.Generic; -using System; - -namespace CSharpScriptRunner -{ - sealed class ReleaseInfo - { - [JsonPropertyName("tag_name")] - public string Version { get; set; } - - [JsonPropertyName("html_url")] - public string Url { get; set; } - - [JsonPropertyName("assets")] - public List Assets { get; set; } - - public sealed class Asset - { - [JsonPropertyName("browser_download_url")] - public string DownloadUrl { get; set; } - } - } - - // static class Updates - // { - // const string RequestUri = "https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest"; - // public const string PowershellCommand = - // @"$dir=md ""$Env:Temp\{$(New-Guid)}""; $bkp=$ProgressPreference; $ProgressPreference='SilentlyContinue'; Write-Host 'Downloading...'; Invoke-WebRequest (Invoke-RestMethod -Uri '" + RequestUri + - // @"' | select -Expand assets | select-string -InputObject {$_.browser_download_url} -Pattern '-win\.zip$' | Select -Expand Line -First 1) -OutFile ""$dir\CSX.zip""; Write-Host 'Expanding archive...'; Expand-Archive -Path ""$dir\CSX.zip"" -DestinationPath ""$dir""; & ""$dir\win\x64\CSharpScriptRunner.exe"" 'install'; Remove-Item $dir -Recurse; $ProgressPreference=$bkp; Write-Host 'Done'"; - - // public static async Task CheckForNewRelease() - // { - // // if (!BuildInfo.ReleaseTag.StartsWith('v') || !Version.TryParse(BuildInfo.ReleaseTag.Substring(1), out var version)) - // // return default; - - // using (var httpClient = new HttpClient()) - // { - // httpClient.DefaultRequestHeaders.Accept.Clear(); - // httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - // httpClient.DefaultRequestHeaders.Add("User-Agent", "CSharpScriptRunner"); - // HttpResponseMessage response; - // try { response = await httpClient.GetAsync(RequestUri); } - // catch { return default; } - // if (!response.IsSuccessStatusCode) - // return default; - - // var release = JsonSerializer.Deserialize(await response.Content.ReadAsByteArrayAsync()); - // if (string.IsNullOrEmpty(release.Version) || string.IsNullOrEmpty(release.Url) || !release.Version.StartsWith('v') || !Version.TryParse(release.Version.Substring(1), out var releaseVersion)) - // return default; - - // // if (version < releaseVersion) - // return release; - // } - // return default; - // } - // } -} \ No newline at end of file diff --git a/publish.ps1 b/publish.ps1 index 1e18283..5eee048 100644 --- a/publish.ps1 +++ b/publish.ps1 @@ -1,3 +1,3 @@ dotnet publish -c Release -r win-x86 -o publish/win/x86 -p:ReleaseTag=dev dotnet publish -c Release -r win-x64 -o publish/win/x64 -p:ReleaseTag=dev -dotnet publish -c Release -o publish/any/any -p:ReleaseTag=dev \ No newline at end of file +# dotnet publish -c Release -o publish/any/any -p:ReleaseTag=dev \ No newline at end of file From f15e830f2ca19b2c66fa6fb59e7c89cb9162dffe Mon Sep 17 00:00:00 2001 From: developer Date: Mon, 3 May 2021 06:42:34 +0200 Subject: [PATCH 32/43] Basic REPL --- ...ram.CurrentThreadSynchronizationContext.cs | 50 ++++--- Program.ListRunning.cs | 50 +++++++ Program.New.cs | 21 +-- Program.RunScript.cs | 24 ++-- Program.Update.cs | 27 ++-- Program.cs | 131 +++++++++++------- 6 files changed, 195 insertions(+), 108 deletions(-) create mode 100644 Program.ListRunning.cs diff --git a/Program.CurrentThreadSynchronizationContext.cs b/Program.CurrentThreadSynchronizationContext.cs index 792eac5..fd7d828 100644 --- a/Program.CurrentThreadSynchronizationContext.cs +++ b/Program.CurrentThreadSynchronizationContext.cs @@ -7,40 +7,44 @@ namespace CSharpScriptRunner { static partial class Program { - sealed class CurrentThreadSynchronizationContext : System.Threading.SynchronizationContext + sealed class SynchronizationContextScope : IDisposable { - readonly BlockingCollection<(SendOrPostCallback Callback, object State)> _queue = new(); - // readonly BlockingCollection<(SendOrPostCallback Callback, object State, ManualResetEventSlim Signal)> _queue = new(); - - CurrentThreadSynchronizationContext() { } + readonly SynchronizationContext _syncCtx; + public SynchronizationContextScope() => _syncCtx = SynchronizationContext.Current; - public override void Send(SendOrPostCallback d, object state) + public System.Runtime.CompilerServices.YieldAwaitable Install(SynchronizationContext synchronizationContext) { - // var signal = new ManualResetEventSlim(false); - // _queue.Add((d, state, signal)); - // signal.Wait(); - throw new InvalidOperationException(); + SynchronizationContext.SetSynchronizationContext(synchronizationContext); + return Task.Yield(); } - public override void Post(SendOrPostCallback d, object state) + public void Dispose() { - _queue.Add((d, state)); - // _queue.Add((d, state, null)); + var current = SynchronizationContext.Current; + if (current == _syncCtx) + return; + if (current is IDisposable disposable) + disposable.Dispose(); + SynchronizationContext.SetSynchronizationContext(_syncCtx); } + } - public static int Run(Func> main) + sealed class CurrentThreadSynchronizationContext : System.Threading.SynchronizationContext, IDisposable + { + readonly BlockingCollection<(SendOrPostCallback Callback, object State)> _queue = new(); + int _isRunning; + public CurrentThreadSynchronizationContext() { } + public override void Send(SendOrPostCallback d, object state) => throw new InvalidOperationException(); + public override void Post(SendOrPostCallback d, object state) { - var syncCtx = new CurrentThreadSynchronizationContext(); - SynchronizationContext.SetSynchronizationContext(syncCtx); - var mainTask = main(); - mainTask.ContinueWith(t => syncCtx._queue.CompleteAdding()); - foreach (var item in syncCtx._queue.GetConsumingEnumerable()) - { + _queue.Add((d, state)); + if (Interlocked.Exchange(ref _isRunning, 1) != 0) + return; + foreach (var item in _queue.GetConsumingEnumerable()) item.Callback(item.State); - // item.Signal?.Set(); - } - return (int)mainTask.Result; } + + public void Dispose() => _queue.CompleteAdding(); } } } diff --git a/Program.ListRunning.cs b/Program.ListRunning.cs new file mode 100644 index 0000000..117150c --- /dev/null +++ b/Program.ListRunning.cs @@ -0,0 +1,50 @@ +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace CSharpScriptRunner +{ + static partial class Program + { + static async Task ListRunning() + { + WriteLine("Process ID RT Arguments"); + WriteLine("---------- --- ---------"); + using var thisProcess = Process.GetCurrentProcess(); + var runtimesDir = Path.GetDirectoryName(thisProcess.MainModule.FileName); // bin + runtimesDir = Path.GetDirectoryName(runtimesDir); // x64 + runtimesDir = Path.GetDirectoryName(runtimesDir); // vX.Y.Z + foreach (var runtimeDir in Directory.EnumerateDirectories(runtimesDir)) + { + var dir = Path.Combine(runtimeDir, "bin", "running"); + if (!Directory.Exists(dir)) + continue; + + var rt = Path.GetFileName(runtimeDir); + + foreach (var file in Directory.EnumerateFiles(dir)) + { + var processId = Path.GetFileNameWithoutExtension(file); + if (thisProcess.Id == int.Parse(processId)) + continue; + + try + { + File.Delete(file); + continue; + } + catch { } + + using var reader = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)); + var args = await reader.ReadToEndAsync().ConfigureAwait(false); + if (args.StartsWith('"')) + args = args.Substring(args.IndexOf('"', 1) + 1); + else + args = args.Split(' ', 2).Last(); + WriteLine($"{processId,10} {rt,-3} {args.Trim()}"); + } + } + } + } +} \ No newline at end of file diff --git a/Program.New.cs b/Program.New.cs index c455d57..963dd51 100644 --- a/Program.New.cs +++ b/Program.New.cs @@ -9,23 +9,6 @@ static partial class Program { static void CreateNew(string template) { - // Script method: - // public static bool ExitAndUpdateEngine() - // { - // var count = System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).Length - 1; - // if (count > 0) - // { - // Script.WriteLines(new[] { - // "The script engine cannot be updated, while there are running script instances.", - // $"There are currently {count} running script instances." }, ConsoleColor.Yellow); - // return false; - // } - // var cmd = "{PowershellCommandEscaped}".Replace("\"", "\\\""); - // System.Diagnostics.Process.Start(new ProcessStartInfo { FileName = "powershell", Arguments = $"-NoExit -Command \"{cmd}\"", UseShellExecute = true }); - // Environment.Exit(0); - // return true; - // } - var templates = typeof(Program).Assembly.GetManifestResourceNames() .Where(x => string.Equals(Path.GetExtension(x), ".csx", StringComparison.OrdinalIgnoreCase)) .ToDictionary(x => Path.GetExtension(Path.GetFileNameWithoutExtension(x)).Substring(1), StringComparer.OrdinalIgnoreCase); @@ -40,14 +23,14 @@ static void CreateNew(string template) if (!templates.TryGetValue(template, out var resName)) { - WriteLine($"The template '{template}' does not exists.", ConsoleColor.Red); + WriteLineError($"The template '{template}' does not exists.", ConsoleColor.Red); return; } var filename = template + ".csx"; if (File.Exists(filename)) { - WriteLine($"The file '{filename} already exists.", ConsoleColor.Red); + WriteLineError($"The file '{filename} already exists.", ConsoleColor.Red); return; } diff --git a/Program.RunScript.cs b/Program.RunScript.cs index a8f3c58..0579418 100644 --- a/Program.RunScript.cs +++ b/Program.RunScript.cs @@ -8,6 +8,7 @@ using System.Text; using System.Text.Json; using System.Text.RegularExpressions; +using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Scripting; @@ -27,7 +28,7 @@ sealed class Config static async Task RunScript(string[] arguments) { - const string NuGetReferenceRegex = @"^\s*#r\s+""\s*nuget:\s*(?[\w\d.-]+)\s*\/\s*(?[\w\d.-]+)\s*""\s*$"; + const string NuGetReferenceRegex = @"^\s*#r\s+""\s*nuget:\s*(?[\w\d.-]+)\s*[\/,]\s*(?[\w\d.-]+)\s*""\s*$"; IEnumerable args = arguments; var runtimeExt = string.Empty; @@ -39,7 +40,7 @@ static async Task RunScript(string[] arguments) runtimeExt = arg.Substring(2); else { - WriteLine($"Argument {arg} is not recognized.", ConsoleColor.Red); + WriteLineError($"Argument {arg} is not recognized.", ConsoleColor.Red); return ErrorCodes.UnrecognizedArgument; } } @@ -47,7 +48,7 @@ static async Task RunScript(string[] arguments) var filePath = args.FirstOrDefault(); if (!File.Exists(filePath)) { - WriteLine($"Script file '{filePath}' does not exist.", ConsoleColor.Red); + WriteLineError($"Script file '{filePath}' does not exist.", ConsoleColor.Red); return ErrorCodes.ScriptFileDoesNotExist; } @@ -100,12 +101,17 @@ static async Task RunScript(string[] arguments) if (entryPoint == null) throw new Exception($"Entry point '{config.Type}.{config.Method}' not found"); - // Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath); - var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), assemblyLoader } }); - var errorCode = (ErrorCodes?)((await task) as int?) ?? ErrorCodes.OK; - if (errorCode > ErrorCodes.OK && errorCode <= ErrorCodes.Reserved) - return ErrorCodes.ScriptReturnRangeConflict; - return errorCode; + // Clear SynchronizationContext to mimic standard console app behavior in script + using (var nullSyncCtxScope = new SynchronizationContextScope()) + { + await nullSyncCtxScope.Install(null); + + var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), assemblyLoader } }); + var errorCode = (ErrorCodes?)((await task) as int?) ?? ErrorCodes.OK; + if (errorCode > ErrorCodes.OK && errorCode <= ErrorCodes.Reserved) + return ErrorCodes.ScriptReturnRangeConflict; + return errorCode; + } static string GetCacheFilenameBase(string filename) { diff --git a/Program.Update.cs b/Program.Update.cs index 83396bd..1b35b25 100644 --- a/Program.Update.cs +++ b/Program.Update.cs @@ -32,7 +32,7 @@ public sealed class Asset public string DownloadUrl { get; set; } } } - + static async Task Update() { const string UpdateMutexName = "C371A9A2-6CBE-43DE-B834-AC8F73E47705"; @@ -40,14 +40,14 @@ static async Task Update() using var mutex = new Mutex(true, UpdateMutexName); if (!mutex.WaitOne(0, true)) { - WriteLine($"{Verbs.Update} command is already running", ConsoleColor.Red); + WriteLineError($"{Verbs.Update} command is already running", ConsoleColor.Red); return; } WriteLine("Checking for new version..."); using var httpClient = new HttpClient(); - httpClient.Timeout = Timeout.InfiniteTimeSpan; + // httpClient.Timeout = Timeout.InfiniteTimeSpan; httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("User-Agent", nameof(CSharpScriptRunner)); @@ -65,14 +65,14 @@ static async Task Update() try { Directory.Delete(dir, true); } catch { continue; } } - WriteLine($"${nameof(CSharpScriptRunner)} is up-to-date ({BuildInfo.ReleaseTag})", ConsoleColor.Green); + WriteLine($"{nameof(CSharpScriptRunner)} is up-to-date ({BuildInfo.ReleaseTag})", ConsoleColor.Green); return; } var tmpDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner), Guid.NewGuid().ToString()); if (Directory.Exists(dstDir)) { - WriteLine($"Newest version ({release.Version}) is already isntalled", ConsoleColor.Green); + WriteLine($"Newest version ({release.Version}) is already installed", ConsoleColor.Green); return; } @@ -82,7 +82,7 @@ static async Task Update() var downloadUrl = release.Assets.Select(x => x.DownloadUrl).FirstOrDefault(x => x.EndsWith($"-{platform}.zip", StringComparison.OrdinalIgnoreCase)); if (downloadUrl == null) { - WriteLine("Operation failed", ConsoleColor.Red); + WriteLineError("Operation failed", ConsoleColor.Red); return; } @@ -115,9 +115,11 @@ static async Task Update() ms.Seek(0, SeekOrigin.Begin); using (var archive = new ZipArchive(ms, ZipArchiveMode.Read)) { - foreach (var entry in archive.Entries) + WriteLine("Extracting..."); + var progress = string.Empty; + for (int i = 0; i < archive.Entries.Count; i++) { - Console.WriteLine($"Extracting {entry.FullName} ..."); + var entry = archive.Entries[i]; var parts = entry.FullName.Split('/'); parts = parts.Take(1).Append("bin").Concat(parts.Skip(1)).Prepend(tmpDir).ToArray(); var dstPath = Path.Combine(parts); @@ -125,7 +127,16 @@ static async Task Update() using var src = entry.Open(); using var dst = new FileStream(dstPath, FileMode.Create); await src.CopyToAsync(dst); + var newProgress = $"{(double)(i + 1) / archive.Entries.Count,4:P0}"; + if (newProgress != progress) + { + progress = newProgress; + try { Console.CursorLeft = 0; } + catch { } + Console.Write(progress); + } } + Console.WriteLine(); } } diff --git a/Program.cs b/Program.cs index d826455..63fb938 100644 --- a/Program.cs +++ b/Program.cs @@ -51,6 +51,7 @@ static class Verbs public const string ClearCache = "clear-cache"; public const string InitVSCode = "init-vscode"; public const string ListRunning = "list-running"; + public const string Repl = "repl"; } enum ErrorCodes @@ -68,18 +69,21 @@ enum ErrorCodes // Must run on STA thread (for WinForms/WPF support) static int Main(string[] args) { - return CurrentThreadSynchronizationContext.Run(() => MainAsync(args)); + // return CurrentThreadSynchronizationContext.Run(async () => (int)(await MainAsync(args))); + return (int)MainAsync(args).Result; } static async Task MainAsync(string[] args) { + using var syncCtxScope = new SynchronizationContextScope(); + await syncCtxScope.Install(new CurrentThreadSynchronizationContext()); using var thisProcess = Process.GetCurrentProcess(); var dir = Path.Combine(Path.GetDirectoryName(thisProcess.MainModule.FileName), "running"); Directory.CreateDirectory(dir); using var file = new FileStream(Path.Combine(dir, thisProcess.Id.ToString()), FileMode.Create, FileAccess.Write, FileShare.Read, 512, FileOptions.DeleteOnClose | FileOptions.Asynchronous); using (var writer = new StreamWriter(file, null, -1, true)) - await writer.WriteLineAsync(Environment.CommandLine); + await writer.WriteAsync(Environment.CommandLine); Console.WriteLine($"{nameof(CSharpScriptRunner)}, {BuildInfo.ReleaseTag}"); @@ -93,6 +97,7 @@ static async Task MainAsync(string[] args) { switch (args[0].ToLowerInvariant()) { + default: return await RunScript(args); case Verbs.Version: break; case Verbs.Install: await Install(args.Length > 1 ? string.Equals(args[1], "inplace", StringComparison.OrdinalIgnoreCase) : false); break; case Verbs.Update: await Update(); break; @@ -100,14 +105,14 @@ static async Task MainAsync(string[] args) case Verbs.ClearCache: await ClearCache(); break; case Verbs.InitVSCode: InitVSCode(); break; case Verbs.ListRunning: await ListRunning(); break; - default: return await RunScript(args); + case Verbs.Repl: await DoRepl(); break; } } catch (Exception ex) { if (ex is AggregateException aggregateException) ex = aggregateException.InnerException; - WriteLine(ex.ToString(), ConsoleColor.Red); + WriteLineError(ex.ToString(), ConsoleColor.Red); return ErrorCodes.GenericError; } return ErrorCodes.OK; @@ -116,29 +121,29 @@ static async Task MainAsync(string[] args) static void PrintHelp() { var exe = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName); - Console.WriteLine($"Alias: {CmdAlias}"); - Console.WriteLine($"{exe} [-r] ScriptFilePath [args]"); - Console.WriteLine($" Executes the specified script."); - Console.WriteLine($" : Runtime, e.g. x86/x64"); - Console.WriteLine($"{exe} {Verbs.Install}"); - Console.WriteLine($" Installs {exe} for the current user."); - Console.WriteLine($"{exe} {Verbs.Update}"); - Console.WriteLine($" Updates {exe} for the current user."); - Console.WriteLine($"{exe} {Verbs.New} [template]"); - Console.WriteLine($" If a template name is provided, a new script file [template].csx is created."); - Console.WriteLine($" If the template name is omitted, the available templates are listed."); - Console.WriteLine($"{exe} {Verbs.InitVSCode}"); - Console.WriteLine($" Initializes VS Code debugging support (creates .vscode directory)"); - Console.WriteLine($"{exe} {Verbs.ClearCache}"); - Console.WriteLine($" Cleares the cache of previously compiled scripts."); - Console.WriteLine($"{exe} {Verbs.ListRunning}"); - Console.WriteLine($" Lists the currently running script engine instances."); + Console.WriteLine($"Alias: {CmdAlias}, {exe}"); + Console.WriteLine($"{CmdAlias} [-r] ScriptFilePath [args]"); + Console.WriteLine($" Executes the specified script."); + Console.WriteLine($" : Runtime, e.g. x86/x64"); + Console.WriteLine($"{CmdAlias} {Verbs.Install}"); + Console.WriteLine($" Installs {exe} for the current user."); + Console.WriteLine($"{CmdAlias} {Verbs.Update}"); + Console.WriteLine($" Updates {exe} for the current user."); + Console.WriteLine($"{CmdAlias} {Verbs.New} [template]"); + Console.WriteLine($" If a template name is provided, a new script file [template].csx is created."); + Console.WriteLine($" If the template name is omitted, the available templates are listed."); + Console.WriteLine($"{CmdAlias} {Verbs.InitVSCode}"); + Console.WriteLine($" Initializes VS Code debugging support (creates .vscode directory)"); + Console.WriteLine($"{CmdAlias} {Verbs.ClearCache}"); + Console.WriteLine($" Cleares the cache of previously compiled scripts."); + Console.WriteLine($"{CmdAlias} {Verbs.ListRunning}"); + Console.WriteLine($" Lists the currently running script engine instances."); Console.WriteLine($"Returned error codes:"); foreach (var code in Enum.GetValues().Where(x => x != ErrorCodes.Reserved)) - Console.WriteLine($" - {code,3:D} {code}"); - Console.WriteLine($" - Value returned by script."); - Console.WriteLine($" Values {ErrorCodes.OK + 1:D} - {ErrorCodes.Reserved:D} are reserved by the engine."); - Console.WriteLine($" If a script returns a value in the reserved range, {ErrorCodes.ScriptReturnRangeConflict} will be returned instead."); + Console.WriteLine($" - {code,3:D} {code}"); + Console.WriteLine($" - Value returned by script."); + Console.WriteLine($" Values {ErrorCodes.OK + 1:D} - {ErrorCodes.Reserved:D} are reserved by the engine."); + Console.WriteLine($" If a script returns a value in the reserved range, {ErrorCodes.ScriptReturnRangeConflict} will be returned instead."); } static void WriteLine(string line, ConsoleColor color = (ConsoleColor)(-1)) @@ -149,36 +154,64 @@ static void WriteLine(string line, ConsoleColor color = (ConsoleColor)(-1)) Console.ResetColor(); } - static async Task ListRunning() + static void WriteLineError(string line, ConsoleColor color = (ConsoleColor)(-1)) { - WriteLine("Process ID RT Arguments"); - WriteLine("---------- --- ---------"); - using var thisProcess = Process.GetCurrentProcess(); - var runtimesDir = Path.GetDirectoryName(thisProcess.MainModule.FileName); // bin - runtimesDir = Path.GetDirectoryName(runtimesDir); // x64 - runtimesDir = Path.GetDirectoryName(runtimesDir); // vX.Y.Z - foreach (var runtimeDir in Directory.EnumerateDirectories(runtimesDir)) + if ((int)color > -1) + Console.ForegroundColor = color; + Console.Error.WriteLine(line); + Console.ResetColor(); + } + + static async Task DoRepl() + { + try { Console.CursorLeft = Console.CursorLeft; } + catch { - var dir = Path.Combine(runtimeDir, "bin", "running"); - if (!Directory.Exists(dir)) - continue; + WriteLineError("REPL not supported in current terminal", ConsoleColor.Red); + return; + } - var rt = Path.GetFileName(runtimeDir); + var script = CSharpScript.Create(string.Empty); - foreach (var file in Directory.EnumerateFiles(dir)) + while (true) + { + Console.Write("> "); + var line = Console.ReadLine(); + + if (string.Equals(line.TrimEnd(), "#reset", StringComparison.OrdinalIgnoreCase)) + { + script = CSharpScript.Create(string.Empty); + continue; + } + + var newScript = script.ContinueWith(line); + var succeeded = true; + var color = Console.ForegroundColor; + foreach (var diag in newScript.Compile()) { - var processId = Path.GetFileNameWithoutExtension(file); - if (thisProcess.Id == int.Parse(processId)) - continue; - - using var reader = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)); - var args = await reader.ReadToEndAsync().ConfigureAwait(false); - if (args.StartsWith('"')) - args = args.Substring(args.IndexOf('"', 1) + 1).TrimStart(); - else - args = args.Split(' ', 2).Last(); - WriteLine($"{processId,10} {rt,-3} {args}"); + switch (diag.Severity) + { + case DiagnosticSeverity.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; + case DiagnosticSeverity.Error: succeeded = false; Console.ForegroundColor = ConsoleColor.Red; break; + default: Console.ForegroundColor = color; break; + } + + var loc = diag.Location.GetLineSpan(); + Console.WriteLine($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}"); } + Console.ForegroundColor = color; + + if (!succeeded) + continue; + + var result = await newScript.RunAsync(); + if (result.ReturnValue is string output) + output = SymbolDisplay.FormatLiteral(output, true); + else + output = result.ReturnValue?.ToString(); + if (!string.IsNullOrEmpty(output)) + WriteLine(output); + script = newScript; } } } From 1794e59de34585f9372b84806432d36976547238 Mon Sep 17 00:00:00 2001 From: developer Date: Sat, 15 May 2021 16:08:33 +0200 Subject: [PATCH 33/43] Use Terminal.Gui package for REPL --- CSharpScriptRunner.csproj | 3 + Program.Repl.cs | 106 ++++++++++++++++++++++++++++ Program.cs | 142 +++++++++++++++++++++++++------------- 3 files changed, 203 insertions(+), 48 deletions(-) create mode 100644 Program.Repl.cs diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index eefb983..fc17b70 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -16,7 +16,9 @@ + + @@ -25,6 +27,7 @@ + diff --git a/Program.Repl.cs b/Program.Repl.cs new file mode 100644 index 0000000..152dc3c --- /dev/null +++ b/Program.Repl.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Scripting; +using Microsoft.CodeAnalysis.Scripting; +using Terminal.Gui; + +namespace CSharpScriptRunner +{ + static partial class Program + { + static async Task DoRepl() + { + using var scope = new SynchronizationContextScope(); + await scope.Install(null); + Application.Init(); + Application.Top.Add(new ReplApp()); + Application.Run(); + } + + sealed class ReplApp : Window + { + readonly TextView _ctrlHistory; + readonly TextField _ctrlInput; + readonly ListView _ctrlIntellisense; + Script _script; + bool _isProcessing = false; + + public ReplApp() + : base($"{nameof(CSharpScriptRunner)} REPL") + { + _ctrlHistory = new() { X = 0, Y = 0, Width = Dim.Fill(), Height = Dim.Fill(1), ReadOnly = true }; + + Label labelInput = new() { X = 0, Y = Pos.Bottom(_ctrlHistory), Height = 1, Text = "> " }; + + _ctrlInput = new() { X = Pos.Right(labelInput), Y = Pos.Bottom(_ctrlHistory), Width = Dim.Fill(), Height = 1 }; + + _ctrlIntellisense = new() { X = 0, Y = 0, Visible = false }; + _ctrlIntellisense.SetSource(new[] { "Item 1", "Item 2", "Item 3" }); + + Add(_ctrlHistory, labelInput, _ctrlInput, _ctrlIntellisense); + _ctrlInput.SetFocus(); + + _ctrlHistory.KeyPress += OnKeyPressHistory; + _ctrlInput.KeyPress += OnKeyPressInput; + + _script = CSharpScript.Create(string.Empty); + } + + void OnKeyPressHistory(View.KeyEventEventArgs args) + { + if (args.KeyEvent.Key == Key.Tab) + { + args.Handled = true; + _ctrlInput.SetFocus(); + } + } + + async void OnKeyPressInput(View.KeyEventEventArgs args) + { + if (args.KeyEvent.Key == Key.Enter) + { + if (_ctrlInput.Text.IsEmpty || _isProcessing) + return; + + _isProcessing = true; + var code = _ctrlInput.Text.ToString(); + var newScript = _script.ContinueWith(code); + var diagnostics = newScript.Compile(); + + var output = new List(); + output.Add($"> {code}"); + var success = true; + foreach (var diag in diagnostics) + { + if (diag.Severity == DiagnosticSeverity.Error) + success = false; + var loc = diag.Location.GetLineSpan(); + output.Add($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}"); + } + + if (success) + { + var result = await newScript.RunAsync(); + if (result.ReturnValue is string value) + value = SymbolDisplay.FormatLiteral(value, true); + else + value = result.ReturnValue?.ToString(); + if (!string.IsNullOrEmpty(value)) + output.Add(value); + _script = newScript; + } + + output.Add(string.Empty); + _ctrlHistory.Text += string.Join(Environment.NewLine, output); + _ctrlHistory.MoveEnd(); + _ctrlInput.Text = string.Empty; + _isProcessing = false; + } + } + } + } +} \ No newline at end of file diff --git a/Program.cs b/Program.cs index 63fb938..e5fc6d7 100644 --- a/Program.cs +++ b/Program.cs @@ -21,6 +21,9 @@ using System.IO.Compression; using System.Net.Http; using System.Net.Http.Headers; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.Completion; namespace CSharpScriptRunner { @@ -39,7 +42,7 @@ static partial class Program const string UpdateRequestUri = "https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest"; const string PowershellUpdateCommand = @"$dir=md ""$Env:Temp\{$(New-Guid)}""; $bkp=$ProgressPreference; $ProgressPreference='SilentlyContinue'; Write-Host 'Downloading...'; Invoke-WebRequest (Invoke-RestMethod -Uri '" + UpdateRequestUri + - @"' | select -Expand assets | select-string -InputObject {$_.browser_download_url} -Pattern '-win\.zip$' | Select -Expand Line -First 1) -OutFile ""$dir\CSX.zip""; Write-Host 'Expanding archive...'; Expand-Archive -Path ""$dir\CSX.zip"" -DestinationPath ""$dir""; & ""$dir\win\x64\CSharpScriptRunner.exe"" 'install'; Remove-Item $dir -Recurse; $ProgressPreference=$bkp; Write-Host 'Done'"; + @"' | select -Expand assets | select-string -InputObject {$_.browser_download_url} -Pattern '-win\.zip$' | Select -Expand Line -First 1) -OutFile ""$dir\CSX.zip""; Write-Host 'Expanding archive...'; Expand-Archive -Path ""$dir\CSX.zip"" -DestinationPath ""$dir""; & ""$dir\x64\CSharpScriptRunner.exe"" 'install'; Remove-Item $dir -Recurse; $ProgressPreference=$bkp; Write-Host 'Done'"; static class Verbs @@ -162,57 +165,100 @@ static void WriteLineError(string line, ConsoleColor color = (ConsoleColor)(-1)) Console.ResetColor(); } - static async Task DoRepl() - { - try { Console.CursorLeft = Console.CursorLeft; } - catch - { - WriteLineError("REPL not supported in current terminal", ConsoleColor.Red); - return; - } + // static async Task DoRepl() + // { + // try { Console.CursorLeft = Console.CursorLeft; } + // catch + // { + // WriteLineError("REPL not supported in current terminal", ConsoleColor.Red); + // return; + // } - var script = CSharpScript.Create(string.Empty); + // var script = CSharpScript.Create(string.Empty); - while (true) - { - Console.Write("> "); - var line = Console.ReadLine(); + // // https://www.strathweb.com/2018/12/using-roslyn-c-completion-service-programmatically/ + // var host = MefHostServices.DefaultHost; + // var ws = new AdhocWorkspace(host); + // var projectId = ProjectId.CreateNewId(); + // var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Default, "Script", "Script", LanguageNames.CSharp, isSubmission: true) + // .WithCompilationOptions(script.GetCompilation().Options) + // .WithMetadataReferences(script.GetCompilation().References); - if (string.Equals(line.TrimEnd(), "#reset", StringComparison.OrdinalIgnoreCase)) - { - script = CSharpScript.Create(string.Empty); - continue; - } + // var project = ws.AddProject(projectInfo); + // var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "Script", sourceCodeKind: SourceCodeKind.Script); + // var doc = ws.AddDocument(docInfo); - var newScript = script.ContinueWith(line); - var succeeded = true; - var color = Console.ForegroundColor; - foreach (var diag in newScript.Compile()) - { - switch (diag.Severity) - { - case DiagnosticSeverity.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; - case DiagnosticSeverity.Error: succeeded = false; Console.ForegroundColor = ConsoleColor.Red; break; - default: Console.ForegroundColor = color; break; - } - - var loc = diag.Location.GetLineSpan(); - Console.WriteLine($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}"); - } - Console.ForegroundColor = color; + // var source = new StringBuilder(); + // var line = new StringBuilder(); - if (!succeeded) - continue; - - var result = await newScript.RunAsync(); - if (result.ReturnValue is string output) - output = SymbolDisplay.FormatLiteral(output, true); - else - output = result.ReturnValue?.ToString(); - if (!string.IsNullOrEmpty(output)) - WriteLine(output); - script = newScript; - } - } + // while (true) + // { + // Console.Write("> "); + // source.Clear(); + // source.Append(script.Code); + // line.Clear(); + // while (true) + // { + // var keyInfo = Console.ReadKey(true); + // line.Append(keyInfo.KeyChar); + // source.Append(keyInfo.KeyChar); + // Console.Write(keyInfo.KeyChar); + // if (keyInfo.Key == ConsoleKey.Enter) + // break; + // doc = doc.WithText(SourceText.From(source.ToString())); + // var service = CompletionService.GetService(doc); + // var items = await service.GetCompletionsAsync(doc, source.Length); + // if (items == null) + // continue; + // var left = Console.CursorLeft; + // var top = Console.CursorTop; + // foreach (var item in items.Items) + // { + // if (Console.CursorTop == 0) + // break; + // Console.CursorTop--; + // Console.Write(item.DisplayText); + // Console.CursorLeft = left; + // } + // Console.CursorTop = top; + // } + + // if (string.Equals(line.ToString().TrimEnd(), "#reset", StringComparison.OrdinalIgnoreCase)) + // { + // script = CSharpScript.Create(string.Empty); + // continue; + // } + + + // var newScript = script.ContinueWith(line.ToString()); + // var succeeded = true; + // var color = Console.ForegroundColor; + // foreach (var diag in newScript.Compile()) + // { + // switch (diag.Severity) + // { + // case DiagnosticSeverity.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; + // case DiagnosticSeverity.Error: succeeded = false; Console.ForegroundColor = ConsoleColor.Red; break; + // default: Console.ForegroundColor = color; break; + // } + + // var loc = diag.Location.GetLineSpan(); + // Console.WriteLine($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}"); + // } + // Console.ForegroundColor = color; + + // if (!succeeded) + // continue; + + // var result = await newScript.RunAsync(); + // if (result.ReturnValue is string output) + // output = SymbolDisplay.FormatLiteral(output, true); + // else + // output = result.ReturnValue?.ToString(); + // if (!string.IsNullOrEmpty(output)) + // WriteLine(output); + // script = newScript; + // } + // } } } From 636153b455805cb6dfbedd10f66c5a7d7d61edce Mon Sep 17 00:00:00 2001 From: ArgusMagnus Date: Mon, 20 Sep 2021 07:31:51 +0200 Subject: [PATCH 34/43] REPL: Basic intellisense support --- CSharpScriptRunner.csproj | 18 ++--- Program.Repl.cs | 146 +++++++++++++++++++++++++++++++++++--- 2 files changed, 146 insertions(+), 18 deletions(-) diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index fc17b70..b641886 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -16,18 +16,18 @@ - - - + + + - - - - - + + + + + - + diff --git a/Program.Repl.cs b/Program.Repl.cs index 152dc3c..0bed910 100644 --- a/Program.Repl.cs +++ b/Program.Repl.cs @@ -3,9 +3,12 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Scripting; +using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Scripting; +using Microsoft.CodeAnalysis.Text; using Terminal.Gui; namespace CSharpScriptRunner @@ -23,31 +26,66 @@ static async Task DoRepl() sealed class ReplApp : Window { + const int MaxIntellisenseHeight = 10; readonly TextView _ctrlHistory; readonly TextField _ctrlInput; readonly ListView _ctrlIntellisense; Script _script; + string _scriptCode = string.Empty; bool _isProcessing = false; + Document _doc; + AdhocWorkspace _ws; + ProjectId _projectId; + int _idxIntellisense; public ReplApp() - : base($"{nameof(CSharpScriptRunner)} REPL") + : base($"{nameof(CSharpScriptRunner)} REPL, {BuildInfo.ReleaseTag}") { - _ctrlHistory = new() { X = 0, Y = 0, Width = Dim.Fill(), Height = Dim.Fill(1), ReadOnly = true }; + ColorScheme = new() + { + Normal = new(Color.White, Color.Black), + Focus = new(Color.White, Color.Black), + Disabled = new(Color.White, Color.Black), + HotNormal = new(Color.White, Color.Black), + HotFocus = new(Color.White, Color.Black) + }; + + Label labelInput = new() { X = 0, Y = Pos.AnchorEnd() - 1, Height = 1, Text = "> " }; + _ctrlInput = new() { X = Pos.Right(labelInput), Y = Pos.AnchorEnd() - 1, Width = Dim.Fill(), Height = 1 }; - Label labelInput = new() { X = 0, Y = Pos.Bottom(_ctrlHistory), Height = 1, Text = "> " }; + _ctrlHistory = new() { X = 0, Y = 0, Width = Dim.Fill(), Height = Dim.Fill() - Dim.Height(_ctrlInput), ReadOnly = true }; - _ctrlInput = new() { X = Pos.Right(labelInput), Y = Pos.Bottom(_ctrlHistory), Width = Dim.Fill(), Height = 1 }; + _ctrlIntellisense = new() { X = 0, Y = 0, Height = MaxIntellisenseHeight, Visible = false }; + _ctrlIntellisense.ColorScheme = new() + { + Normal = new(Color.White, Color.DarkGray), + HotNormal = new(Color.White, Color.Blue), + Focus = new(Color.White, Color.DarkGray), + HotFocus = new(Color.White, Color.Blue) + }; - _ctrlIntellisense = new() { X = 0, Y = 0, Visible = false }; - _ctrlIntellisense.SetSource(new[] { "Item 1", "Item 2", "Item 3" }); + Add(_ctrlHistory, _ctrlIntellisense, labelInput, _ctrlInput); - Add(_ctrlHistory, labelInput, _ctrlInput, _ctrlIntellisense); _ctrlInput.SetFocus(); _ctrlHistory.KeyPress += OnKeyPressHistory; _ctrlInput.KeyPress += OnKeyPressInput; + _ctrlInput.KeyUp += OnKeyUpInput; + _ctrlInput.TextChanged += OnTextChangedInput; _script = CSharpScript.Create(string.Empty); + + // https://www.strathweb.com/2018/12/using-roslyn-c-completion-service-programmatically/ + var host = MefHostServices.DefaultHost; + _ws = new AdhocWorkspace(host); + _projectId = ProjectId.CreateNewId(); + var projectInfo = ProjectInfo.Create(_projectId, VersionStamp.Default, "Script", "Script", LanguageNames.CSharp, isSubmission: true) + .WithCompilationOptions(_script.GetCompilation().Options) + .WithMetadataReferences(_script.GetCompilation().References); + + var project = _ws.AddProject(projectInfo); + var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(_projectId), "Script", sourceCodeKind: SourceCodeKind.Script); + _doc = _ws.AddDocument(docInfo); } void OnKeyPressHistory(View.KeyEventEventArgs args) @@ -59,7 +97,45 @@ void OnKeyPressHistory(View.KeyEventEventArgs args) } } - async void OnKeyPressInput(View.KeyEventEventArgs args) + void OnKeyPressInput(View.KeyEventEventArgs args) + { + if (_ctrlIntellisense.Visible) + { + switch (args.KeyEvent.Key) + { + default: return; + + case Key.CursorDown: + if (_ctrlIntellisense.SelectedItem == _ctrlIntellisense.Source.Count - 1) + _ctrlIntellisense.MoveHome(); + else + _ctrlIntellisense.MoveDown(); + break; + + case Key.CursorUp: + if (_ctrlIntellisense.SelectedItem == 0) + _ctrlIntellisense.MoveEnd(); + else + _ctrlIntellisense.MoveUp(); + break; + + case Key.Tab: + var item = _ctrlIntellisense.Source.ToList()[_ctrlIntellisense.SelectedItem].ToString(); + var text = _ctrlInput.Text.ToString(); + var cursorsPos = text.Length + item.Length; + text = text.Substring(0, _idxIntellisense) + item; + _ctrlInput.Text = text; + _ctrlInput.CursorPosition = cursorsPos; + _ctrlIntellisense.Visible = false; + break; + } + + _ctrlIntellisense.SetNeedsDisplay(); + args.Handled = true; + } + } + + async void OnKeyUpInput(View.KeyEventEventArgs args) { if (args.KeyEvent.Key == Key.Enter) { @@ -67,7 +143,7 @@ async void OnKeyPressInput(View.KeyEventEventArgs args) return; _isProcessing = true; - var code = _ctrlInput.Text.ToString(); + var code = _ctrlInput.Text.ToString().TrimEnd(); var newScript = _script.ContinueWith(code); var diagnostics = newScript.Compile(); @@ -92,6 +168,9 @@ async void OnKeyPressInput(View.KeyEventEventArgs args) if (!string.IsNullOrEmpty(value)) output.Add(value); _script = newScript; + if (!code.EndsWith(';')) + code += ';'; + _scriptCode += code; } output.Add(string.Empty); @@ -100,6 +179,55 @@ async void OnKeyPressInput(View.KeyEventEventArgs args) _ctrlInput.Text = string.Empty; _isProcessing = false; } + else if (args.KeyEvent.Key == Key.CursorLeft || args.KeyEvent.Key == Key.CursorRight) + { + OnTextChangedInput(_ctrlInput.Text); + } + } + + async void OnTextChangedInput(NStack.ustring oldText) + { + if (_ctrlInput.Text.IsEmpty) + { + _ctrlIntellisense.Visible = false; + return; + } + + var code = _scriptCode + _ctrlInput.Text.ToString(); + var doc = _doc.WithText(SourceText.From(code)); + var service = CompletionService.GetService(doc); + var completion = await service.GetCompletionsAsync(doc, Math.Min(_ctrlInput.CursorPosition + _scriptCode.Length, code.Length)); + if (completion == null) + { + _ctrlIntellisense.Visible = false; + return; + } + + var items = completion.Items; + if (items != null) + { + var filter = code.Substring(0, Math.Min(_ctrlInput.CursorPosition + _scriptCode.Length, code.Length)); + var idx = filter.LastIndexOfAny(completion.Rules.DefaultCommitCharacters.ToArray()); + if (idx > -1) + filter = filter.Substring(idx); + items = service.FilterItems(doc, items, filter); + _idxIntellisense = idx + 1 - _scriptCode.Length; + } + + if (items.Length == 0) + _ctrlIntellisense.Visible = false; + else + { + var completionItems = items.Select(x => x.DisplayText).ToList(); + _ctrlIntellisense.SetSource(completionItems); + _ctrlIntellisense.X = Pos.Left(_ctrlInput) + _idxIntellisense; + + + _ctrlIntellisense.Y = Pos.Top(_ctrlInput) - Math.Min(completionItems.Count, MaxIntellisenseHeight); + _ctrlIntellisense.Width = _ctrlIntellisense.Maxlength; + // _ctrlIntellisense.Height = height; + _ctrlIntellisense.Visible = true; + } } } } From 8e628b03459d06f8e5451d4485d9e21be997f728 Mon Sep 17 00:00:00 2001 From: ArgusMagnus Date: Mon, 20 Sep 2021 08:03:16 +0200 Subject: [PATCH 35/43] Ref: Moved ReplApp out of Program class --- Program.Repl.cs | 217 ----------------------------------------------- ReplApp.cs | 221 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 221 insertions(+), 217 deletions(-) create mode 100644 ReplApp.cs diff --git a/Program.Repl.cs b/Program.Repl.cs index 0bed910..422611d 100644 --- a/Program.Repl.cs +++ b/Program.Repl.cs @@ -1,14 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Completion; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Scripting; -using Microsoft.CodeAnalysis.Host.Mef; -using Microsoft.CodeAnalysis.Scripting; -using Microsoft.CodeAnalysis.Text; using Terminal.Gui; namespace CSharpScriptRunner @@ -23,212 +13,5 @@ static async Task DoRepl() Application.Top.Add(new ReplApp()); Application.Run(); } - - sealed class ReplApp : Window - { - const int MaxIntellisenseHeight = 10; - readonly TextView _ctrlHistory; - readonly TextField _ctrlInput; - readonly ListView _ctrlIntellisense; - Script _script; - string _scriptCode = string.Empty; - bool _isProcessing = false; - Document _doc; - AdhocWorkspace _ws; - ProjectId _projectId; - int _idxIntellisense; - - public ReplApp() - : base($"{nameof(CSharpScriptRunner)} REPL, {BuildInfo.ReleaseTag}") - { - ColorScheme = new() - { - Normal = new(Color.White, Color.Black), - Focus = new(Color.White, Color.Black), - Disabled = new(Color.White, Color.Black), - HotNormal = new(Color.White, Color.Black), - HotFocus = new(Color.White, Color.Black) - }; - - Label labelInput = new() { X = 0, Y = Pos.AnchorEnd() - 1, Height = 1, Text = "> " }; - _ctrlInput = new() { X = Pos.Right(labelInput), Y = Pos.AnchorEnd() - 1, Width = Dim.Fill(), Height = 1 }; - - _ctrlHistory = new() { X = 0, Y = 0, Width = Dim.Fill(), Height = Dim.Fill() - Dim.Height(_ctrlInput), ReadOnly = true }; - - _ctrlIntellisense = new() { X = 0, Y = 0, Height = MaxIntellisenseHeight, Visible = false }; - _ctrlIntellisense.ColorScheme = new() - { - Normal = new(Color.White, Color.DarkGray), - HotNormal = new(Color.White, Color.Blue), - Focus = new(Color.White, Color.DarkGray), - HotFocus = new(Color.White, Color.Blue) - }; - - Add(_ctrlHistory, _ctrlIntellisense, labelInput, _ctrlInput); - - _ctrlInput.SetFocus(); - - _ctrlHistory.KeyPress += OnKeyPressHistory; - _ctrlInput.KeyPress += OnKeyPressInput; - _ctrlInput.KeyUp += OnKeyUpInput; - _ctrlInput.TextChanged += OnTextChangedInput; - - _script = CSharpScript.Create(string.Empty); - - // https://www.strathweb.com/2018/12/using-roslyn-c-completion-service-programmatically/ - var host = MefHostServices.DefaultHost; - _ws = new AdhocWorkspace(host); - _projectId = ProjectId.CreateNewId(); - var projectInfo = ProjectInfo.Create(_projectId, VersionStamp.Default, "Script", "Script", LanguageNames.CSharp, isSubmission: true) - .WithCompilationOptions(_script.GetCompilation().Options) - .WithMetadataReferences(_script.GetCompilation().References); - - var project = _ws.AddProject(projectInfo); - var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(_projectId), "Script", sourceCodeKind: SourceCodeKind.Script); - _doc = _ws.AddDocument(docInfo); - } - - void OnKeyPressHistory(View.KeyEventEventArgs args) - { - if (args.KeyEvent.Key == Key.Tab) - { - args.Handled = true; - _ctrlInput.SetFocus(); - } - } - - void OnKeyPressInput(View.KeyEventEventArgs args) - { - if (_ctrlIntellisense.Visible) - { - switch (args.KeyEvent.Key) - { - default: return; - - case Key.CursorDown: - if (_ctrlIntellisense.SelectedItem == _ctrlIntellisense.Source.Count - 1) - _ctrlIntellisense.MoveHome(); - else - _ctrlIntellisense.MoveDown(); - break; - - case Key.CursorUp: - if (_ctrlIntellisense.SelectedItem == 0) - _ctrlIntellisense.MoveEnd(); - else - _ctrlIntellisense.MoveUp(); - break; - - case Key.Tab: - var item = _ctrlIntellisense.Source.ToList()[_ctrlIntellisense.SelectedItem].ToString(); - var text = _ctrlInput.Text.ToString(); - var cursorsPos = text.Length + item.Length; - text = text.Substring(0, _idxIntellisense) + item; - _ctrlInput.Text = text; - _ctrlInput.CursorPosition = cursorsPos; - _ctrlIntellisense.Visible = false; - break; - } - - _ctrlIntellisense.SetNeedsDisplay(); - args.Handled = true; - } - } - - async void OnKeyUpInput(View.KeyEventEventArgs args) - { - if (args.KeyEvent.Key == Key.Enter) - { - if (_ctrlInput.Text.IsEmpty || _isProcessing) - return; - - _isProcessing = true; - var code = _ctrlInput.Text.ToString().TrimEnd(); - var newScript = _script.ContinueWith(code); - var diagnostics = newScript.Compile(); - - var output = new List(); - output.Add($"> {code}"); - var success = true; - foreach (var diag in diagnostics) - { - if (diag.Severity == DiagnosticSeverity.Error) - success = false; - var loc = diag.Location.GetLineSpan(); - output.Add($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}"); - } - - if (success) - { - var result = await newScript.RunAsync(); - if (result.ReturnValue is string value) - value = SymbolDisplay.FormatLiteral(value, true); - else - value = result.ReturnValue?.ToString(); - if (!string.IsNullOrEmpty(value)) - output.Add(value); - _script = newScript; - if (!code.EndsWith(';')) - code += ';'; - _scriptCode += code; - } - - output.Add(string.Empty); - _ctrlHistory.Text += string.Join(Environment.NewLine, output); - _ctrlHistory.MoveEnd(); - _ctrlInput.Text = string.Empty; - _isProcessing = false; - } - else if (args.KeyEvent.Key == Key.CursorLeft || args.KeyEvent.Key == Key.CursorRight) - { - OnTextChangedInput(_ctrlInput.Text); - } - } - - async void OnTextChangedInput(NStack.ustring oldText) - { - if (_ctrlInput.Text.IsEmpty) - { - _ctrlIntellisense.Visible = false; - return; - } - - var code = _scriptCode + _ctrlInput.Text.ToString(); - var doc = _doc.WithText(SourceText.From(code)); - var service = CompletionService.GetService(doc); - var completion = await service.GetCompletionsAsync(doc, Math.Min(_ctrlInput.CursorPosition + _scriptCode.Length, code.Length)); - if (completion == null) - { - _ctrlIntellisense.Visible = false; - return; - } - - var items = completion.Items; - if (items != null) - { - var filter = code.Substring(0, Math.Min(_ctrlInput.CursorPosition + _scriptCode.Length, code.Length)); - var idx = filter.LastIndexOfAny(completion.Rules.DefaultCommitCharacters.ToArray()); - if (idx > -1) - filter = filter.Substring(idx); - items = service.FilterItems(doc, items, filter); - _idxIntellisense = idx + 1 - _scriptCode.Length; - } - - if (items.Length == 0) - _ctrlIntellisense.Visible = false; - else - { - var completionItems = items.Select(x => x.DisplayText).ToList(); - _ctrlIntellisense.SetSource(completionItems); - _ctrlIntellisense.X = Pos.Left(_ctrlInput) + _idxIntellisense; - - - _ctrlIntellisense.Y = Pos.Top(_ctrlInput) - Math.Min(completionItems.Count, MaxIntellisenseHeight); - _ctrlIntellisense.Width = _ctrlIntellisense.Maxlength; - // _ctrlIntellisense.Height = height; - _ctrlIntellisense.Visible = true; - } - } - } } } \ No newline at end of file diff --git a/ReplApp.cs b/ReplApp.cs new file mode 100644 index 0000000..48288e8 --- /dev/null +++ b/ReplApp.cs @@ -0,0 +1,221 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Completion; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Scripting; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Scripting; +using Microsoft.CodeAnalysis.Text; +using Terminal.Gui; + +namespace CSharpScriptRunner +{ + sealed class ReplApp : Window + { + const int MaxIntellisenseHeight = 10; + readonly TextView _ctrlHistory; + readonly TextField _ctrlInput; + readonly ListView _ctrlIntellisense; + Script _script; + string _scriptCode = string.Empty; + bool _isProcessing = false; + Document _doc; + AdhocWorkspace _ws; + ProjectId _projectId; + int _idxIntellisense; + + public ReplApp() + : base($"{nameof(CSharpScriptRunner)} REPL, {BuildInfo.ReleaseTag}") + { + ColorScheme = new() + { + Normal = new(Color.White, Color.Black), + Focus = new(Color.White, Color.Black), + Disabled = new(Color.White, Color.Black), + HotNormal = new(Color.White, Color.Black), + HotFocus = new(Color.White, Color.Black) + }; + + Label labelInput = new() { X = 0, Y = Pos.AnchorEnd() - 1, Height = 1, Text = "> " }; + _ctrlInput = new() { X = Pos.Right(labelInput), Y = Pos.AnchorEnd() - 1, Width = Dim.Fill(), Height = 1 }; + + _ctrlHistory = new() { X = 0, Y = 0, Width = Dim.Fill(), Height = Dim.Fill() - Dim.Height(_ctrlInput), ReadOnly = true }; + + _ctrlIntellisense = new() { X = 0, Y = 0, Height = MaxIntellisenseHeight, Visible = false }; + _ctrlIntellisense.ColorScheme = new() + { + Normal = new(Color.White, Color.DarkGray), + HotNormal = new(Color.White, Color.Blue), + Focus = new(Color.White, Color.DarkGray), + HotFocus = new(Color.White, Color.Blue) + }; + + Add(_ctrlHistory, _ctrlIntellisense, labelInput, _ctrlInput); + + _ctrlInput.SetFocus(); + + _ctrlHistory.KeyPress += OnKeyPressHistory; + _ctrlInput.KeyPress += OnKeyPressInput; + _ctrlInput.KeyUp += OnKeyUpInput; + _ctrlInput.TextChanged += OnTextChangedInput; + + _script = CSharpScript.Create(string.Empty); + + // https://www.strathweb.com/2018/12/using-roslyn-c-completion-service-programmatically/ + var host = MefHostServices.DefaultHost; + _ws = new AdhocWorkspace(host); + _projectId = ProjectId.CreateNewId(); + var projectInfo = ProjectInfo.Create(_projectId, VersionStamp.Default, "Script", "Script", LanguageNames.CSharp, isSubmission: true) + .WithCompilationOptions(_script.GetCompilation().Options) + .WithMetadataReferences(_script.GetCompilation().References); + + var project = _ws.AddProject(projectInfo); + var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(_projectId), "Script", sourceCodeKind: SourceCodeKind.Script); + _doc = _ws.AddDocument(docInfo); + } + + void OnKeyPressHistory(View.KeyEventEventArgs args) + { + if (args.KeyEvent.Key == Key.Tab) + { + args.Handled = true; + _ctrlInput.SetFocus(); + } + } + + void OnKeyPressInput(View.KeyEventEventArgs args) + { + if (_ctrlIntellisense.Visible) + { + switch (args.KeyEvent.Key) + { + default: return; + + case Key.CursorDown: + if (_ctrlIntellisense.SelectedItem == _ctrlIntellisense.Source.Count - 1) + _ctrlIntellisense.MoveHome(); + else + _ctrlIntellisense.MoveDown(); + break; + + case Key.CursorUp: + if (_ctrlIntellisense.SelectedItem == 0) + _ctrlIntellisense.MoveEnd(); + else + _ctrlIntellisense.MoveUp(); + break; + + case Key.Tab: + var item = _ctrlIntellisense.Source.ToList()[_ctrlIntellisense.SelectedItem].ToString(); + var text = _ctrlInput.Text.ToString(); + var cursorsPos = text.Length + item.Length; + text = text.Substring(0, _idxIntellisense) + item; + _ctrlInput.Text = text; + _ctrlInput.CursorPosition = cursorsPos; + _ctrlIntellisense.Visible = false; + break; + } + + _ctrlIntellisense.SetNeedsDisplay(); + args.Handled = true; + } + } + + async void OnKeyUpInput(View.KeyEventEventArgs args) + { + if (args.KeyEvent.Key == Key.Enter) + { + if (_ctrlInput.Text.IsEmpty || _isProcessing) + return; + + _isProcessing = true; + var code = _ctrlInput.Text.ToString().TrimEnd(); + var newScript = _script.ContinueWith(code); + var diagnostics = newScript.Compile(); + + var output = new List(); + output.Add($"> {code}"); + var success = true; + foreach (var diag in diagnostics) + { + if (diag.Severity == DiagnosticSeverity.Error) + success = false; + var loc = diag.Location.GetLineSpan(); + output.Add($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}"); + } + + if (success) + { + var result = await newScript.RunAsync(); + if (result.ReturnValue is string value) + value = SymbolDisplay.FormatLiteral(value, true); + else + value = result.ReturnValue?.ToString(); + if (!string.IsNullOrEmpty(value)) + output.Add(value); + _script = newScript; + if (!code.EndsWith(';')) + code += ';'; + _scriptCode += code; + } + + output.Add(string.Empty); + _ctrlHistory.Text += string.Join(Environment.NewLine, output); + _ctrlHistory.MoveEnd(); + _ctrlInput.Text = string.Empty; + _isProcessing = false; + } + else if (args.KeyEvent.Key == Key.CursorLeft || args.KeyEvent.Key == Key.CursorRight) + { + OnTextChangedInput(_ctrlInput.Text); + } + } + + async void OnTextChangedInput(NStack.ustring oldText) + { + if (_ctrlInput.Text.IsEmpty) + { + _ctrlIntellisense.Visible = false; + return; + } + + var code = _scriptCode + _ctrlInput.Text.ToString(); + var doc = _doc.WithText(SourceText.From(code)); + var service = CompletionService.GetService(doc); + var completion = await service.GetCompletionsAsync(doc, Math.Min(_ctrlInput.CursorPosition + _scriptCode.Length, code.Length)); + if (completion == null) + { + _ctrlIntellisense.Visible = false; + return; + } + + var items = completion.Items; + if (items != null) + { + var filter = code.Substring(0, Math.Min(_ctrlInput.CursorPosition + _scriptCode.Length, code.Length)); + var idx = filter.LastIndexOfAny(completion.Rules.DefaultCommitCharacters.ToArray()); + if (idx > -1) + filter = filter.Substring(idx); + items = service.FilterItems(doc, items, filter); + _idxIntellisense = idx + 1 - _scriptCode.Length; + } + + if (items.Length == 0) + _ctrlIntellisense.Visible = false; + else + { + var completionItems = items.Select(x => x.DisplayText).ToList(); + _ctrlIntellisense.SetSource(completionItems); + _ctrlIntellisense.X = Pos.Left(_ctrlInput) + _idxIntellisense; + + + _ctrlIntellisense.Y = Pos.Top(_ctrlInput) - Math.Min(completionItems.Count, MaxIntellisenseHeight); + _ctrlIntellisense.Width = _ctrlIntellisense.Maxlength; + // _ctrlIntellisense.Height = height; + _ctrlIntellisense.Visible = true; + } + } + } +} \ No newline at end of file From de78a141bc7f3bf052b5ee5ea383d7a30c7c762f Mon Sep 17 00:00:00 2001 From: ArgusMagnus Date: Sat, 25 Sep 2021 16:36:51 +0200 Subject: [PATCH 36/43] Create README.md --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..92ce29e --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# CSharpScriptRunner +A C# script engine for Windows which does not require admin privileges. + +## Installation + +### PowerShell + + $dir=md "$Env:Temp\{$(New-Guid)}"; $bkp=$ProgressPreference; $ProgressPreference='SilentlyContinue'; Write-Host 'Downloading...'; Invoke-WebRequest (Invoke-RestMethod -Uri 'https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest' | select -Expand assets | select-string -InputObject {$_.browser_download_url} -Pattern '-win\.zip$' | Select -Expand Line -First 1) -OutFile "$dir\CSX.zip"; Write-Host 'Expanding archive...'; Expand-Archive -Path "$dir\CSX.zip" -DestinationPath "$dir"; & "$dir\x64\CSharpScriptRunner.exe" 'install'; Remove-Item $dir -Recurse; $ProgressPreference=$bkp; Write-Host 'Done' + From 6c10337f3ee712e65d4bd113c1604fe842d0d33d Mon Sep 17 00:00:00 2001 From: ArgusMagnus Date: Thu, 28 Apr 2022 16:34:43 +0200 Subject: [PATCH 37/43] add EXPERIMENTAL label --- ReplApp.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ReplApp.cs b/ReplApp.cs index 48288e8..dd0040e 100644 --- a/ReplApp.cs +++ b/ReplApp.cs @@ -27,7 +27,7 @@ sealed class ReplApp : Window int _idxIntellisense; public ReplApp() - : base($"{nameof(CSharpScriptRunner)} REPL, {BuildInfo.ReleaseTag}") + : base($"{nameof(CSharpScriptRunner)} REPL, {BuildInfo.ReleaseTag}, EXPERIMENTAL") { ColorScheme = new() { From 869ab55463cca4f0e186388a2baad76ab27043bd Mon Sep 17 00:00:00 2001 From: ArgusMagnus Date: Thu, 28 Apr 2022 16:38:22 +0200 Subject: [PATCH 38/43] removed commented out code --- Program.cs | 96 ------------------------------------------------------ 1 file changed, 96 deletions(-) diff --git a/Program.cs b/Program.cs index e5fc6d7..3596f58 100644 --- a/Program.cs +++ b/Program.cs @@ -164,101 +164,5 @@ static void WriteLineError(string line, ConsoleColor color = (ConsoleColor)(-1)) Console.Error.WriteLine(line); Console.ResetColor(); } - - // static async Task DoRepl() - // { - // try { Console.CursorLeft = Console.CursorLeft; } - // catch - // { - // WriteLineError("REPL not supported in current terminal", ConsoleColor.Red); - // return; - // } - - // var script = CSharpScript.Create(string.Empty); - - // // https://www.strathweb.com/2018/12/using-roslyn-c-completion-service-programmatically/ - // var host = MefHostServices.DefaultHost; - // var ws = new AdhocWorkspace(host); - // var projectId = ProjectId.CreateNewId(); - // var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Default, "Script", "Script", LanguageNames.CSharp, isSubmission: true) - // .WithCompilationOptions(script.GetCompilation().Options) - // .WithMetadataReferences(script.GetCompilation().References); - - // var project = ws.AddProject(projectInfo); - // var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "Script", sourceCodeKind: SourceCodeKind.Script); - // var doc = ws.AddDocument(docInfo); - - // var source = new StringBuilder(); - // var line = new StringBuilder(); - - // while (true) - // { - // Console.Write("> "); - // source.Clear(); - // source.Append(script.Code); - // line.Clear(); - // while (true) - // { - // var keyInfo = Console.ReadKey(true); - // line.Append(keyInfo.KeyChar); - // source.Append(keyInfo.KeyChar); - // Console.Write(keyInfo.KeyChar); - // if (keyInfo.Key == ConsoleKey.Enter) - // break; - // doc = doc.WithText(SourceText.From(source.ToString())); - // var service = CompletionService.GetService(doc); - // var items = await service.GetCompletionsAsync(doc, source.Length); - // if (items == null) - // continue; - // var left = Console.CursorLeft; - // var top = Console.CursorTop; - // foreach (var item in items.Items) - // { - // if (Console.CursorTop == 0) - // break; - // Console.CursorTop--; - // Console.Write(item.DisplayText); - // Console.CursorLeft = left; - // } - // Console.CursorTop = top; - // } - - // if (string.Equals(line.ToString().TrimEnd(), "#reset", StringComparison.OrdinalIgnoreCase)) - // { - // script = CSharpScript.Create(string.Empty); - // continue; - // } - - - // var newScript = script.ContinueWith(line.ToString()); - // var succeeded = true; - // var color = Console.ForegroundColor; - // foreach (var diag in newScript.Compile()) - // { - // switch (diag.Severity) - // { - // case DiagnosticSeverity.Warning: Console.ForegroundColor = ConsoleColor.Yellow; break; - // case DiagnosticSeverity.Error: succeeded = false; Console.ForegroundColor = ConsoleColor.Red; break; - // default: Console.ForegroundColor = color; break; - // } - - // var loc = diag.Location.GetLineSpan(); - // Console.WriteLine($"{diag.Severity} ({loc.StartLinePosition.Line}, {loc.StartLinePosition.Character}): {diag.GetMessage()}"); - // } - // Console.ForegroundColor = color; - - // if (!succeeded) - // continue; - - // var result = await newScript.RunAsync(); - // if (result.ReturnValue is string output) - // output = SymbolDisplay.FormatLiteral(output, true); - // else - // output = result.ReturnValue?.ToString(); - // if (!string.IsNullOrEmpty(output)) - // WriteLine(output); - // script = newScript; - // } - // } } } From 410188474968c8912ee5d345bef1af6ba2b597b4 Mon Sep 17 00:00:00 2001 From: ArgusMagnus Date: Thu, 28 Apr 2022 16:58:50 +0200 Subject: [PATCH 39/43] set tfm to net6.0-windows --- CSharpScriptRunner.csproj | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index b641886..17d89b6 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -3,7 +3,7 @@ C# Script Runner Exe - net5.0-windows + net6.0-windows true true true @@ -16,18 +16,18 @@ - - - + + + - - - - - + + + + + - + From b5bbff5baab35709389a7227ddcf93046ce911bc Mon Sep 17 00:00:00 2001 From: ArgusMagnus Date: Thu, 28 Apr 2022 19:06:22 +0200 Subject: [PATCH 40/43] add --self-contained --- publish.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/publish.ps1 b/publish.ps1 index 5eee048..18ff5bd 100644 --- a/publish.ps1 +++ b/publish.ps1 @@ -1,3 +1,3 @@ -dotnet publish -c Release -r win-x86 -o publish/win/x86 -p:ReleaseTag=dev -dotnet publish -c Release -r win-x64 -o publish/win/x64 -p:ReleaseTag=dev +dotnet publish -c Release -r win-x86 -o publish/win/x86 -p:ReleaseTag=dev --self-contained +dotnet publish -c Release -r win-x64 -o publish/win/x64 -p:ReleaseTag=dev --self-contained # dotnet publish -c Release -o publish/any/any -p:ReleaseTag=dev \ No newline at end of file From e30e861f913dff8a198ff6d72297b2950f6c5559 Mon Sep 17 00:00:00 2001 From: ArgusMagnus Date: Fri, 29 Apr 2022 08:08:02 +0200 Subject: [PATCH 41/43] make sure scripts run on STA thread --- Program.CurrentThreadSynchronizationContext.cs | 13 ++++++++++++- Program.Repl.cs | 4 ++-- Program.RunScript.cs | 4 +++- Program.cs | 8 ++++++-- 4 files changed, 23 insertions(+), 6 deletions(-) diff --git a/Program.CurrentThreadSynchronizationContext.cs b/Program.CurrentThreadSynchronizationContext.cs index fd7d828..40bea18 100644 --- a/Program.CurrentThreadSynchronizationContext.cs +++ b/Program.CurrentThreadSynchronizationContext.cs @@ -10,16 +10,27 @@ static partial class Program sealed class SynchronizationContextScope : IDisposable { readonly SynchronizationContext _syncCtx; + bool _isDisposed = true; public SynchronizationContextScope() => _syncCtx = SynchronizationContext.Current; - public System.Runtime.CompilerServices.YieldAwaitable Install(SynchronizationContext synchronizationContext) + public void Install(SynchronizationContext synchronizationContext) { + Dispose(); SynchronizationContext.SetSynchronizationContext(synchronizationContext); + _isDisposed = false; + } + + public System.Runtime.CompilerServices.YieldAwaitable InstallAndYield(SynchronizationContext synchronizationContext) + { + Install(synchronizationContext); return Task.Yield(); } public void Dispose() { + if (_isDisposed) + return; + _isDisposed = true; var current = SynchronizationContext.Current; if (current == _syncCtx) return; diff --git a/Program.Repl.cs b/Program.Repl.cs index 422611d..c7944fc 100644 --- a/Program.Repl.cs +++ b/Program.Repl.cs @@ -5,10 +5,10 @@ namespace CSharpScriptRunner { static partial class Program { - static async Task DoRepl() + static void DoRepl() { using var scope = new SynchronizationContextScope(); - await scope.Install(null); + scope.Install(null); Application.Init(); Application.Top.Add(new ReplApp()); Application.Run(); diff --git a/Program.RunScript.cs b/Program.RunScript.cs index 0579418..e9a09ce 100644 --- a/Program.RunScript.cs +++ b/Program.RunScript.cs @@ -104,7 +104,9 @@ static async Task RunScript(string[] arguments) // Clear SynchronizationContext to mimic standard console app behavior in script using (var nullSyncCtxScope = new SynchronizationContextScope()) { - await nullSyncCtxScope.Install(null); + nullSyncCtxScope.Install(null); + + Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.STA); var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), assemblyLoader } }); var errorCode = (ErrorCodes?)((await task) as int?) ?? ErrorCodes.OK; diff --git a/Program.cs b/Program.cs index 3596f58..100c76e 100644 --- a/Program.cs +++ b/Program.cs @@ -11,6 +11,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; +using System.Threading; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Scripting; @@ -79,7 +80,8 @@ static int Main(string[] args) static async Task MainAsync(string[] args) { using var syncCtxScope = new SynchronizationContextScope(); - await syncCtxScope.Install(new CurrentThreadSynchronizationContext()); + await syncCtxScope.InstallAndYield(new CurrentThreadSynchronizationContext()); + Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.STA); using var thisProcess = Process.GetCurrentProcess(); var dir = Path.Combine(Path.GetDirectoryName(thisProcess.MainModule.FileName), "running"); Directory.CreateDirectory(dir); @@ -108,7 +110,7 @@ static async Task MainAsync(string[] args) case Verbs.ClearCache: await ClearCache(); break; case Verbs.InitVSCode: InitVSCode(); break; case Verbs.ListRunning: await ListRunning(); break; - case Verbs.Repl: await DoRepl(); break; + case Verbs.Repl: DoRepl(); break; } } catch (Exception ex) @@ -141,6 +143,8 @@ static void PrintHelp() Console.WriteLine($" Cleares the cache of previously compiled scripts."); Console.WriteLine($"{CmdAlias} {Verbs.ListRunning}"); Console.WriteLine($" Lists the currently running script engine instances."); + Console.WriteLine($"{CmdAlias} {Verbs.Repl}"); + Console.WriteLine($" Experimental: Enter interactive (REPL) mode."); Console.WriteLine($"Returned error codes:"); foreach (var code in Enum.GetValues().Where(x => x != ErrorCodes.Reserved)) Console.WriteLine($" - {code,3:D} {code}"); From 41979979f74e030a1bd21a84bc606106ab65e856 Mon Sep 17 00:00:00 2001 From: ArgusMagnus Date: Fri, 29 Apr 2022 13:28:08 +0200 Subject: [PATCH 42/43] Update main.yml dotnet-version: '6.0.x' --- .github/workflows/main.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c3c934a..29a1116 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -12,7 +12,7 @@ jobs: - name: Setup .NET Core SDK uses: actions/setup-dotnet@v1 with: - dotnet-version: '5.0.x' + dotnet-version: '6.0.x' - name: Build run: dotnet build -c Release @@ -27,14 +27,14 @@ jobs: - name: Setup .NET Core SDK uses: actions/setup-dotnet@v1 with: - dotnet-version: '5.0.x' + dotnet-version: '6.0.x' - name: Build run: | $version = "${{ github.ref }}" $version = $version.Substring(10) Add-Content -Path $env:GITHUB_ENV -Value "RELEASE_TAG=$version" -Encoding UTF8 - dotnet publish -c Release -r win-x86 -o ./publish/win/x86 -p:ReleaseTag=$version - dotnet publish -c Release -r win-x64 -o ./publish/win/x64 -p:ReleaseTag=$version + dotnet publish -c Release -r win-x86 -o ./publish/win/x86 -p:ReleaseTag=$version --self-contained + dotnet publish -c Release -r win-x64 -o ./publish/win/x64 -p:ReleaseTag=$version --self-contained Compress-Archive -Path ./publish/win/* -DestinationPath ./publish/win.zip -CompressionLevel Optimal - name: Create Release id: create_release From 471af37cf1e842fd82ead79f5899ee32ef2eca40 Mon Sep 17 00:00:00 2001 From: ArgusMagnus Date: Fri, 8 Jul 2022 16:18:28 +0200 Subject: [PATCH 43/43] update templates --- Templates/Script.csx | 12 ++++++++++++ Templates/ScriptUI.csx | 12 ++++++++++++ 2 files changed, 24 insertions(+) diff --git a/Templates/Script.csx b/Templates/Script.csx index 5f8620a..deea2fe 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -46,6 +46,18 @@ static class Script static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId); + + static bool GetIsConsoleOwner() + { + int processId; + GetWindowThreadProcessId(_consoleWindow, out processId); + return processId == System.Diagnostics.Process.GetCurrentProcess().Id; + } + + public static bool IsConsoleOwner { get; } = GetIsConsoleOwner(); + [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index b4c8ff2..42c2091 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -69,6 +69,18 @@ static class Script static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId); + + static bool GetIsConsoleOwner() + { + int processId; + GetWindowThreadProcessId(_consoleWindow, out processId); + return processId == System.Diagnostics.Process.GetCurrentProcess().Id; + } + + public static bool IsConsoleOwner { get; } = GetIsConsoleOwner(); + [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);