diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index e8e5a6e..29a1116 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -8,26 +8,34 @@ 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: '6.0.x' - name: Build run: dotnet build -c Release 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: - - 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: '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 --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 uses: actions/create-release@v1.0.0 @@ -38,18 +46,13 @@ jobs: release_name: Release ${{ github.ref }} draft: false 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 - Compress-Archive -Path ./publish/* -DestinationPath ./publish/win.zip -CompressionLevel Optimal - - 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 }} with: upload_url: ${{ steps.create_release.outputs.upload_url }} asset_path: ./publish/win.zip - asset_name: ${{ github.ref }}-win.zip + asset_name: CSharpScriptRunner-${{ env.RELEASE_TAG }}-win.zip asset_content_type: application/zip diff --git a/.gitignore b/.gitignore index 551e3d1..79f13a8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ bin obj -publish/x64 -publish/x86 +publish/win/x64 +publish/win/x86 +publish/any/any .vscode +.vs diff --git a/CSharpScriptRunner.csproj b/CSharpScriptRunner.csproj index 31526a2..17d89b6 100644 --- a/CSharpScriptRunner.csproj +++ b/CSharpScriptRunner.csproj @@ -1,25 +1,70 @@ - + + C# Script Runner Exe - - netcoreapp3.1 + net6.0-windows + true true true + dev + bin/x64/bin - + - - - - - - - + + + + + + + + + + + + + + + $(IntermediateOutputPath)BuildInfo.cs + + + +namespace CSharpScriptRunner +{ + static class BuildInfo + { + public const string RuntimeIdentifier = "$(RuntimeIdentifier)"%3B + public const string Configuration = "$(Configuration)"%3B + public const string ReleaseTag = "$(ReleaseTag)"%3B + } +} + + + + +namespace CSharpScriptRunner +{ + static class BuildInfo + { + public const string RuntimeIdentifier = "win-x64"%3B + public const string Configuration = "$(Configuration)"%3B + public const string ReleaseTag = "$(ReleaseTag)"%3B + } +} + + + + + + + + + diff --git a/NuGet.cs b/NuGet.cs index d0c18e5..cc88b27 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) + 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 nuGetFramework = NuGetFramework.ParseFolder("netcoreapp3.1"); + 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 = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.NuGetHome), "packages"); + var packagesPath = SettingsUtility.GetGlobalPackagesFolder(settings); + var runtimeFramework = NuGetFramework.ParseFolder(BuildInfo.RuntimeIdentifier); using (var cacheContext = new SourceCacheContext()) { @@ -49,7 +51,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,19 +59,18 @@ await GetPackageDependencies( NullLogger.Instance); var frameworkReducer = new FrameworkReducer(); - var assembliesToLoad = new HashSet(StringComparer.OrdinalIgnoreCase); 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, new PackageDownloadContext(cacheContext), - SettingsUtility.GetGlobalPackagesFolder(settings), + packagesPath, NullLogger.Instance, CancellationToken.None); await PackageExtractor.ExtractPackageAsync( @@ -79,31 +80,36 @@ await PackageExtractor.ExtractPackageAsync( packageExtractionContext, CancellationToken.None); } - + installedPath = packagePathResolver.GetInstalledPath(packageToInstall); - packageReader = new PackageFolderReader(installedPath); - - var libItems = packageReader.GetLibItems(); - var nearest = frameworkReducer.GetNearest(nuGetFramework, libItems.Select(x => x.TargetFramework)); - assembliesToLoad.AddRange(libItems - .Where(x => x.TargetFramework.Equals(nearest)) - .SelectMany(x => x.Items) - .Where(x => x.EndsWith(".dll")) - .Select(x => Path.Combine(installedPath, x))); - - var frameworkItems = packageReader.GetFrameworkItems(); - nearest = frameworkReducer.GetNearest(nuGetFramework, frameworkItems.Select(x => x.TargetFramework)); - - assembliesToLoad.AddRange(frameworkItems - .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); - foreach (var assemblyPath in assembliesToLoad) - { - Assembly.LoadFrom(assemblyPath); + if (buildReferences != null) + { + var items = await packageReader.GetReferenceItemsAsync(CancellationToken.None); + var paths = GetAssemblyPaths(items, frameworkReducer, nuGetFramework, installedPath); + buildReferences.AddRange(paths); + } + + 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); + } } } } @@ -135,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.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..40bea18 --- /dev/null +++ b/Program.CurrentThreadSynchronizationContext.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Concurrent; +using System.Threading.Tasks; +using System.Threading; + +namespace CSharpScriptRunner +{ + static partial class Program + { + sealed class SynchronizationContextScope : IDisposable + { + readonly SynchronizationContext _syncCtx; + bool _isDisposed = true; + public SynchronizationContextScope() => _syncCtx = SynchronizationContext.Current; + + 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; + if (current is IDisposable disposable) + disposable.Dispose(); + SynchronizationContext.SetSynchronizationContext(_syncCtx); + } + } + + 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) + { + _queue.Add((d, state)); + if (Interlocked.Exchange(ref _isRunning, 1) != 0) + return; + foreach (var item in _queue.GetConsumingEnumerable()) + item.Callback(item.State); + } + + public void Dispose() => _queue.CompleteAdding(); + } + } +} 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..befcbbd --- /dev/null +++ b/Program.Install.cs @@ -0,0 +1,129 @@ +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 thisPath = Process.GetCurrentProcess().MainModule.FileName; + var newPath = thisPath; + var filename = Path.GetFileName(thisPath); + var valid = false; + + if (installInPlace) + { + 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)) + { + 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; + + 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)); + 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}"" %*"); + } + } + + if (!valid) + { + WriteLine("Installation failed", ConsoleColor.Red); + return; + } + + 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.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 new file mode 100644 index 0000000..963dd51 --- /dev/null +++ b/Program.New.cs @@ -0,0 +1,50 @@ +using System; +using System.IO; +using System.Linq; +using System.Text; + +namespace CSharpScriptRunner +{ + static partial class Program + { + 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) + { + 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)) + { + WriteLineError($"The template '{template}' does not exists.", ConsoleColor.Red); + return; + } + + var filename = template + ".csx"; + if (File.Exists(filename)) + { + WriteLineError($"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.Repl.cs b/Program.Repl.cs new file mode 100644 index 0000000..c7944fc --- /dev/null +++ b/Program.Repl.cs @@ -0,0 +1,17 @@ +using System.Threading.Tasks; +using Terminal.Gui; + +namespace CSharpScriptRunner +{ + static partial class Program + { + static void DoRepl() + { + using var scope = new SynchronizationContextScope(); + scope.Install(null); + Application.Init(); + Application.Top.Add(new ReplApp()); + Application.Run(); + } + } +} \ No newline at end of file diff --git a/Program.RunScript.cs b/Program.RunScript.cs new file mode 100644 index 0000000..e9a09ce --- /dev/null +++ b/Program.RunScript.cs @@ -0,0 +1,242 @@ +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; +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 + { + WriteLineError($"Argument {arg} is not recognized.", ConsoleColor.Red); + return ErrorCodes.UnrecognizedArgument; + } + } + + var filePath = args.FirstOrDefault(); + if (!File.Exists(filePath)) + { + WriteLineError($"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"); + + // Clear SynchronizationContext to mimic standard console app behavior in script + using (var nullSyncCtxScope = new SynchronizationContextScope()) + { + 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; + if (errorCode > ErrorCodes.OK && errorCode <= ErrorCodes.Reserved) + 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..1b35b25 --- /dev/null +++ b/Program.Update.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +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.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; + +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"; + + using var mutex = new Mutex(true, UpdateMutexName); + if (!mutex.WaitOne(0, true)) + { + 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.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 installed", 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) + { + WriteLineError("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)) + { + WriteLine("Extracting..."); + var progress = string.Empty; + for (int i = 0; i < archive.Entries.Count; i++) + { + 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); + Directory.CreateDirectory(Path.GetDirectoryName(dstPath)); + 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(); + } + } + + 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 3813de3..100c76e 100644 --- a/Program.cs +++ b/Program.cs @@ -11,338 +11,161 @@ 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; using Microsoft.CodeAnalysis.Scripting; using System.Text.RegularExpressions; +using Microsoft.CodeAnalysis.Scripting.Hosting; +using Microsoft.CodeAnalysis.CSharp; +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 { 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 + static partial class Program { - [STAThread] - static void Main(string[] args) - { - if (args == null || args.Length == 0) - return; + const string CmdAlias = "csx"; + static readonly string CachePath = Path.Combine(Path.GetTempPath(), nameof(CSharpScriptRunner)); - try - { - if (args[0] == "install") - Install(); - else if (args[0] == "new") - CreateNew(args.Length > 1 ? args[1] : null); - else - RunScript(args); - } - catch (Exception ex) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine(ex); - System.Threading.Thread.Sleep(5000); - } - } + 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\x64\CSharpScriptRunner.exe"" 'install'; Remove-Item $dir -Recurse; $ProgressPreference=$bkp; Write-Host 'Done'"; - static void Install() - { - var oldPath = Process.GetCurrentProcess().MainModule.FileName; - 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 (!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); - }))).Wait(); - } - - var envPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User) - .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) - .Where(x => !x.Contains(nameof(CSharpScriptRunner))) - .Append(Path.GetDirectoryName(newPath)); - Environment.SetEnvironmentVariable("Path", string.Join(';', envPath), EnvironmentVariableTarget.User); - - var filetype = ".csx"; - - 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\""); - } - - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("Installation was successful."); - Console.ResetColor(); - System.Threading.Thread.Sleep(5000); - } - - static string GetCacheFilenameBase(string filename) + static class Verbs { - 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")); - var dir = Path.Combine(Path.GetTempPath(), nameof(CSharpScriptRunner)); - Directory.CreateDirectory(dir); - return Path.Combine(dir, result.ToString()); - } + 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"; + public const string ListRunning = "list-running"; + public const string Repl = "repl"; } - static byte[] GetFileHash(string filename) + enum ErrorCodes { - var bytes = File.ReadAllBytes(filename); - using (var hasher = SHA256.Create()) - { - return hasher.ComputeHash(bytes); - } + OK = 0, + GenericError, + ScriptReturnRangeConflict, + UnrecognizedArgument, + ScriptFileDoesNotExist, + ScriptCompilationFailed, + Reserved = 0xFF } - sealed class Config + [STAThread] + // Must run on STA thread (for WinForms/WPF support) + static int Main(string[] args) { - public string Type { get; set; } - public string Method { get; set; } + // return CurrentThreadSynchronizationContext.Run(async () => (int)(await MainAsync(args))); + return (int)MainAsync(args).Result; } - static bool TryGetCache(string assemblyFile, string hashFile, string configFile, byte[] scriptHash, out Config config) + static async Task MainAsync(string[] args) { - config = null; - if (!File.Exists(assemblyFile) || !File.Exists(hashFile) || !File.Exists(configFile)) - return false; + using var syncCtxScope = new SynchronizationContextScope(); + 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); - var cachedHash = File.ReadAllBytes(hashFile); - if (!cachedHash.SequenceEqual(scriptHash)) - return false; + 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.WriteAsync(Environment.CommandLine); - var cfgJson = File.ReadAllText(configFile, Encoding.UTF8); - config = JsonSerializer.Deserialize(cfgJson); - return true; - } + Console.WriteLine($"{nameof(CSharpScriptRunner)}, {BuildInfo.ReleaseTag}"); - 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)) + if (args == null || args.Length == 0) { - 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; - } + PrintHelp(); + return ErrorCodes.OK; } - 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; - 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 result = compilation.Emit(assemblyFile); - PrintCompilationDiagnostics(result, lines); - if (!result.Success) - { - System.Threading.Thread.Sleep(5000); - 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 void LoadPackages(string scriptPath) - { - var matches = Regex.Matches(File.ReadAllText(scriptPath), @"^//#AddPackage\s+""(?[\w.-]+),\s*(?[\w.-]+)""\s*$", RegexOptions.Multiline); - foreach (Match match in matches) - NuGet.LoadPackage(match.Groups["name"].Value, match.Groups["version"].Value).Wait(); - } - - static void RunScript(string[] args) - { - var scriptPath = Path.GetFullPath(args[0]); - var runtimeExt = Path.GetExtension(Path.GetFileNameWithoutExtension(scriptPath)); - if (!string.IsNullOrEmpty(runtimeExt)) + try { - runtimeExt = runtimeExt.Substring(1); - var exePath = Process.GetCurrentProcess().MainModule.FileName; - var filename = Path.GetFileName(exePath); - var dir = Path.GetDirectoryName(exePath); - var runtimeDir = Path.GetFileName(dir); - dir = Path.GetDirectoryName(dir); - if (runtimeExt != runtimeDir) + switch (args[0].ToLowerInvariant()) { - exePath = Path.Combine(dir, runtimeExt, filename); - if (File.Exists(exePath)) - { - Process.Start(new ProcessStartInfo(exePath, string.Join(" ", args.Select(x => $"\"{x.Replace("\"", "\\\"")}\""))) { UseShellExecute = false }); - return; - } - - Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine($"Warning: Runtime '{runtimeExt}' was not found. Proceeding anyway..."); - Console.ResetColor(); + 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; + 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; + case Verbs.Repl: DoRepl(); break; } } - - 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)) + catch (Exception ex) { - if (!TryBuild(scriptPath, assemblyFile, hashFile, configFile, scriptHash, out config)) - return; + if (ex is AggregateException aggregateException) + ex = aggregateException.InnerException; + WriteLineError(ex.ToString(), ConsoleColor.Red); + return ErrorCodes.GenericError; } - - var assembly = Assembly.LoadFile(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; - - var arguments = ParseArguments(args); - Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath); - var task = (Task)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(arguments), null } }); - task.Wait(); + return ErrorCodes.OK; } - static void PrintCompilationDiagnostics(EmitResult result, string[] lines) + static void PrintHelp() { - 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; + var exe = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName); + 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($"{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}"); + 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 CreateNew(string template) + static void WriteLine(string line, ConsoleColor color = (ConsoleColor)(-1)) { - var templates = typeof(Program).Assembly.GetManifestResourceNames() - .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(); - } - - if (!templates.TryGetValue(template, out var resName)) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"The template '{template}' does not exists."); - Console.ResetColor(); - return; - } - - var filename = template + ".csx"; - if (File.Exists(filename)) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"The file '{filename} already exists."); - Console.ResetColor(); - return; - } - - using (var res = typeof(Program).Assembly.GetManifestResourceStream(resName)) - using (var file = File.OpenWrite(filename)) - { - res.CopyTo(file); - } + if ((int)color > -1) + Console.ForegroundColor = color; + Console.WriteLine(line); + Console.ResetColor(); + } - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine($"The file '{filename}' was created."); + static void WriteLineError(string line, ConsoleColor color = (ConsoleColor)(-1)) + { + if ((int)color > -1) + Console.ForegroundColor = color; + Console.Error.WriteLine(line); Console.ResetColor(); } } 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' + diff --git a/ReplApp.cs b/ReplApp.cs new file mode 100644 index 0000000..dd0040e --- /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}, EXPERIMENTAL") + { + 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/Templates/Script.csx b/Templates/Script.csx index 41b92f2..deea2fe 100644 --- a/Templates/Script.csx +++ b/Templates/Script.csx @@ -1,8 +1,10 @@ -// 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 '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 // @@ -10,65 +12,113 @@ // .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; +using System.Threading.Tasks; +Script.WriteLine($"Executing script '{Script.ScriptPath}'...", ConsoleColor.Green); 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"); Console.ReadLine(); +return 0; // End of script + #region Utilities -public static class Script +static class Script { - static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; + 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); - [System.Runtime.InteropServices.DllImport("user32.dll")] - static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + 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); - const int SW_HIDE = 0; - const int SW_SHOW = 5; + static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; - 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; + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId); - 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; - } + static bool GetIsConsoleOwner() + { + int processId; + GetWindowThreadProcessId(_consoleWindow, out processId); + return processId == System.Diagnostics.Process.GetCurrentProcess().Id; + } - public static void WriteLines(IEnumerable lines, ConsoleColor color = (ConsoleColor)(-1)) + public static bool IsConsoleOwner { get; } = GetIsConsoleOwner(); + + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + 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; + + 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; + } } #endregion \ No newline at end of file diff --git a/Templates/ScriptUI.csx b/Templates/ScriptUI.csx index 4618354..42c2091 100644 --- a/Templates/ScriptUI.csx +++ b/Templates/ScriptUI.csx @@ -1,8 +1,10 @@ -// 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 '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 // @@ -10,9 +12,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" @@ -33,8 +35,11 @@ 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}")); +Script.WriteLines(Script.ParseArguments(Args).Select(x => $"{x.Key}: {x.Value}")); var window = (Window)XamlReader.Parse(@" MessageBox.Show("Hello World!")); window.ShowDialog(); +return 0; // End of script + #region Utilities -public static class Script +static class Script { - static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; + 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); + public static string EnginePath { get; } = "%CSharpScriptRunnerRuntimesDir%" + System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Substring(Environment.GetEnvironmentVariable("CSharpScriptRunnerRuntimesDir").Length); - [System.Runtime.InteropServices.DllImport("user32.dll")] - static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; - const int SW_HIDE = 0; - const int SW_SHOW = 5; + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId); - 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; + static bool GetIsConsoleOwner() + { + int processId; + GetWindowThreadProcessId(_consoleWindow, out processId); + return processId == System.Diagnostics.Process.GetCurrentProcess().Id; + } - 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 bool IsConsoleOwner { get; } = GetIsConsoleOwner(); - public static void WriteLines(IEnumerable lines, ConsoleColor color = (ConsoleColor)(-1)) + [System.Runtime.InteropServices.DllImport("user32.dll")] + static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + 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; + + 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; + } } #region WPF utility classes -public abstract class NotifyPropertyChanged : INotifyPropertyChanged +abstract class NotifyPropertyChanged : INotifyPropertyChanged { string[] _propertyNames; @@ -152,13 +202,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; @@ -215,7 +265,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())) { } @@ -224,7 +274,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/Templates/vscode/launch.json b/Templates/vscode/launch.json new file mode 100644 index 0000000..ed37232 --- /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": "${env:CSharpScriptRunnerRuntimesDir}/x64/bin/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 diff --git a/publish.ps1 b/publish.ps1 index e5f85b3..18ff5bd 100644 --- a/publish.ps1 +++ b/publish.ps1 @@ -1,2 +1,3 @@ -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/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 diff --git a/publish/install.bat b/publish/install.bat deleted file mode 100644 index d50607a..0000000 --- a/publish/install.bat +++ /dev/null @@ -1 +0,0 @@ -.\x64\CSharpScriptRunner.exe install \ No newline at end of file