Skip to content

Commit c235d21

Browse files
committed
list-running command
1 parent 307a25f commit c235d21

File tree

9 files changed

+121
-97
lines changed

9 files changed

+121
-97
lines changed

CSharpScriptRunner.csproj

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,21 @@
88
<UseWPF>true</UseWPF>
99
<UseWindowsForms>true</UseWindowsForms>
1010
<ReleaseTag>dev</ReleaseTag>
11+
<OutDir>bin/x64/bin</OutDir>
1112
</PropertyGroup>
1213

1314
<ItemGroup>
1415
<EmbeddedResource Include="Templates/**/*.*" />
1516
</ItemGroup>
1617

1718
<ItemGroup>
18-
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="3.8.0" />
19+
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="3.9.0" />
1920
<PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0" />
20-
<PackageReference Include="NuGet.Common" Version="5.8.0" />
21-
<PackageReference Include="NuGet.Configuration" Version="5.8.0" />
22-
<PackageReference Include="NuGet.Packaging" Version="5.8.0" />
23-
<PackageReference Include="NuGet.Protocol" Version="5.8.0" />
24-
<PackageReference Include="NuGet.Resolver" Version="5.8.0" />
21+
<PackageReference Include="NuGet.Common" Version="5.9.1" />
22+
<PackageReference Include="NuGet.Configuration" Version="5.9.1" />
23+
<PackageReference Include="NuGet.Packaging" Version="5.9.1" />
24+
<PackageReference Include="NuGet.Protocol" Version="5.9.1" />
25+
<PackageReference Include="NuGet.Resolver" Version="5.9.1" />
2526
<PackageReference Include="System.IO.FileSystem.Primitives" Version="4.3.0" />
2627
<PackageReference Include="System.Text.Encoding.Extensions" Version="4.3.0" />
2728
</ItemGroup>

Program.Install.cs

Lines changed: 38 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,31 @@ static partial class Program
1111
{
1212
static async Task Install(bool installInPlace)
1313
{
14-
var oldPath = Process.GetCurrentProcess().MainModule.FileName;
15-
var newPath = oldPath;
16-
var filename = Path.GetFileName(oldPath);
17-
var oldDir = Path.GetDirectoryName(oldPath);
18-
var runtimeDir = Path.GetFileName(oldDir);
19-
oldDir = Path.GetDirectoryName(oldDir);
20-
var newDir = oldDir;
14+
var thisPath = Process.GetCurrentProcess().MainModule.FileName;
15+
var newPath = thisPath;
16+
var filename = Path.GetFileName(thisPath);
17+
var valid = false;
2118

22-
if (!installInPlace)
19+
if (installInPlace)
2320
{
24-
newDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner), BuildInfo.ReleaseTag);
21+
var runtimesDir = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(thisPath)));
22+
foreach (var dir in Directory.EnumerateDirectories(runtimesDir))
23+
{
24+
if (!File.Exists(Path.Combine(dir, "bin", filename)))
25+
continue;
26+
27+
valid = true;
28+
29+
File.WriteAllText(Path.Combine(dir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*");
30+
File.WriteAllText(Path.Combine(dir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*");
31+
}
32+
}
33+
else
34+
{
35+
var oldDir = Path.GetDirectoryName(thisPath);
36+
var runtimeDir = Path.GetFileName(oldDir);
37+
oldDir = Path.GetDirectoryName(oldDir);
38+
var newDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), nameof(CSharpScriptRunner), BuildInfo.ReleaseTag);
2539
newPath = Path.Combine(newDir, runtimeDir, "bin", filename);
2640
if (Directory.Exists(newDir))
2741
{
@@ -42,27 +56,32 @@ static async Task Install(bool installInPlace)
4256
}
4357
}
4458
Directory.CreateDirectory(newDir);
45-
}
4659

47-
foreach (var dir in Directory.EnumerateDirectories(oldDir))
48-
{
49-
if (!File.Exists(Path.Combine(dir, filename)))
50-
continue;
51-
52-
var dstDir = Path.Combine(newDir, Path.GetFileName(dir));
53-
if (!installInPlace)
60+
foreach (var dir in Directory.EnumerateDirectories(oldDir))
5461
{
62+
if (!File.Exists(Path.Combine(dir, filename)))
63+
continue;
64+
65+
valid = true;
66+
67+
var dstDir = Path.Combine(newDir, Path.GetFileName(dir));
5568
await Task.WhenAll(Directory.EnumerateFiles(dir, "*", new EnumerationOptions { RecurseSubdirectories = true }).Select(file => Task.Run(() =>
5669
{
5770
var dst = Path.Combine(dstDir, "bin", file.Substring(dir.Length + 1));
5871
Directory.CreateDirectory(Path.GetDirectoryName(dst));
5972
Console.WriteLine($"Copying {dst} ...");
6073
File.Copy(file, dst, true);
6174
})));
75+
76+
File.WriteAllText(Path.Combine(dstDir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*");
77+
File.WriteAllText(Path.Combine(dstDir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*");
6278
}
79+
}
6380

64-
File.WriteAllText(Path.Combine(dstDir, Path.ChangeExtension(filename, ".cmd")), $@"@echo off & ""%~dp0bin\{filename}"" %*");
65-
File.WriteAllText(Path.Combine(dstDir, $"{CmdAlias}.cmd"), $@"@echo off & ""%~dp0bin\{filename}"" %*");
81+
if (!valid)
82+
{
83+
WriteLine("Installation failed", ConsoleColor.Red);
84+
return;
6685
}
6786

6887
var envPath = (Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User)

Program.RunScript.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ sealed class Config
2828
static async Task<ErrorCodes> RunScript(string[] arguments)
2929
{
3030
const string NuGetReferenceRegex = @"^\s*#r\s+""\s*nuget:\s*(?<name>[\w\d.-]+)\s*\/\s*(?<version>[\w\d.-]+)\s*""\s*$";
31-
31+
3232
IEnumerable<string> args = arguments;
3333
var runtimeExt = string.Empty;
3434
while (args.FirstOrDefault()?.StartsWith('-') ?? false)
@@ -103,7 +103,7 @@ static async Task<ErrorCodes> RunScript(string[] arguments)
103103
// Environment.CurrentDirectory = Path.GetDirectoryName(scriptPath);
104104
var task = (Task<object>)entryPoint.Invoke(null, new object[] { new object[] { new ScriptGlobals(args.Skip(1).ToArray()), assemblyLoader } });
105105
var errorCode = (ErrorCodes?)((await task) as int?) ?? ErrorCodes.OK;
106-
if ((errorCode & ErrorCodes.ErrorMask) != default)
106+
if (errorCode > ErrorCodes.OK && errorCode <= ErrorCodes.Reserved)
107107
return ErrorCodes.ScriptReturnRangeConflict;
108108
return errorCode;
109109

Program.Update.cs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,38 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.Diagnostics;
34
using System.IO;
45
using System.IO.Compression;
56
using System.Linq;
67
using System.Net.Http;
78
using System.Net.Http.Headers;
89
using System.Text.Json;
10+
using System.Text.Json.Serialization;
911
using System.Threading;
1012
using System.Threading.Tasks;
1113

1214
namespace CSharpScriptRunner
1315
{
1416
static partial class Program
1517
{
18+
sealed class ReleaseInfo
19+
{
20+
[JsonPropertyName("tag_name")]
21+
public string Version { get; set; }
22+
23+
[JsonPropertyName("html_url")]
24+
public string Url { get; set; }
25+
26+
[JsonPropertyName("assets")]
27+
public List<Asset> Assets { get; set; }
28+
29+
public sealed class Asset
30+
{
31+
[JsonPropertyName("browser_download_url")]
32+
public string DownloadUrl { get; set; }
33+
}
34+
}
35+
1636
static async Task Update()
1737
{
1838
const string UpdateMutexName = "C371A9A2-6CBE-43DE-B834-AC8F73E47705";
@@ -95,7 +115,7 @@ static async Task Update()
95115
ms.Seek(0, SeekOrigin.Begin);
96116
using (var archive = new ZipArchive(ms, ZipArchiveMode.Read))
97117
{
98-
await Task.WhenAll(archive.Entries.Select(async entry =>
118+
foreach (var entry in archive.Entries)
99119
{
100120
Console.WriteLine($"Extracting {entry.FullName} ...");
101121
var parts = entry.FullName.Split('/');
@@ -105,7 +125,7 @@ await Task.WhenAll(archive.Entries.Select(async entry =>
105125
using var src = entry.Open();
106126
using var dst = new FileStream(dstPath, FileMode.Create);
107127
await src.CopyToAsync(dst);
108-
}));
128+
}
109129
}
110130
}
111131

Program.cs

Lines changed: 48 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,17 +50,18 @@ static class Verbs
5050
public const string New = "new";
5151
public const string ClearCache = "clear-cache";
5252
public const string InitVSCode = "init-vscode";
53+
public const string ListRunning = "list-running";
5354
}
5455

55-
enum ErrorCodes : uint
56+
enum ErrorCodes
5657
{
5758
OK = 0,
58-
ErrorMask = 0xFF000000,
59-
ScriptReturnRangeConflict = 0x01_00_00_00,
6059
GenericError,
60+
ScriptReturnRangeConflict,
6161
UnrecognizedArgument,
6262
ScriptFileDoesNotExist,
6363
ScriptCompilationFailed,
64+
Reserved = 0xFF
6465
}
6566

6667
[STAThread]
@@ -76,7 +77,7 @@ static async Task<ErrorCodes> MainAsync(string[] args)
7677
var dir = Path.Combine(Path.GetDirectoryName(thisProcess.MainModule.FileName), "running");
7778
Directory.CreateDirectory(dir);
7879

79-
using var file = new FileStream(Path.Combine(dir, thisProcess.Id.ToString()), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 512, FileOptions.DeleteOnClose | FileOptions.Asynchronous);
80+
using var file = new FileStream(Path.Combine(dir, thisProcess.Id.ToString()), FileMode.Create, FileAccess.Write, FileShare.Read, 512, FileOptions.DeleteOnClose | FileOptions.Asynchronous);
8081
using (var writer = new StreamWriter(file, null, -1, true))
8182
await writer.WriteLineAsync(Environment.CommandLine);
8283

@@ -98,6 +99,7 @@ static async Task<ErrorCodes> MainAsync(string[] args)
9899
case Verbs.New: CreateNew(args.Length > 1 ? args[1] : null); break;
99100
case Verbs.ClearCache: await ClearCache(); break;
100101
case Verbs.InitVSCode: InitVSCode(); break;
102+
case Verbs.ListRunning: await ListRunning(); break;
101103
default: return await RunScript(args);
102104
}
103105
}
@@ -129,7 +131,15 @@ static void PrintHelp()
129131
Console.WriteLine($" Initializes VS Code debugging support (creates .vscode directory)");
130132
Console.WriteLine($"{exe} {Verbs.ClearCache}");
131133
Console.WriteLine($" Cleares the cache of previously compiled scripts.");
132-
}
134+
Console.WriteLine($"{exe} {Verbs.ListRunning}");
135+
Console.WriteLine($" Lists the currently running script engine instances.");
136+
Console.WriteLine($"Returned error codes:");
137+
foreach (var code in Enum.GetValues<ErrorCodes>().Where(x => x != ErrorCodes.Reserved))
138+
Console.WriteLine($" - {code,3:D} {code}");
139+
Console.WriteLine($" - Value returned by script.");
140+
Console.WriteLine($" Values {ErrorCodes.OK + 1:D} - {ErrorCodes.Reserved:D} are reserved by the engine.");
141+
Console.WriteLine($" If a script returns a value in the reserved range, {ErrorCodes.ScriptReturnRangeConflict} will be returned instead.");
142+
}
133143

134144
static void WriteLine(string line, ConsoleColor color = (ConsoleColor)(-1))
135145
{
@@ -138,5 +148,38 @@ static void WriteLine(string line, ConsoleColor color = (ConsoleColor)(-1))
138148
Console.WriteLine(line);
139149
Console.ResetColor();
140150
}
151+
152+
static async Task ListRunning()
153+
{
154+
WriteLine("Process ID RT Arguments");
155+
WriteLine("---------- --- ---------");
156+
using var thisProcess = Process.GetCurrentProcess();
157+
var runtimesDir = Path.GetDirectoryName(thisProcess.MainModule.FileName); // bin
158+
runtimesDir = Path.GetDirectoryName(runtimesDir); // x64
159+
runtimesDir = Path.GetDirectoryName(runtimesDir); // vX.Y.Z
160+
foreach (var runtimeDir in Directory.EnumerateDirectories(runtimesDir))
161+
{
162+
var dir = Path.Combine(runtimeDir, "bin", "running");
163+
if (!Directory.Exists(dir))
164+
continue;
165+
166+
var rt = Path.GetFileName(runtimeDir);
167+
168+
foreach (var file in Directory.EnumerateFiles(dir))
169+
{
170+
var processId = Path.GetFileNameWithoutExtension(file);
171+
if (thisProcess.Id == int.Parse(processId))
172+
continue;
173+
174+
using var reader = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete));
175+
var args = await reader.ReadToEndAsync().ConfigureAwait(false);
176+
if (args.StartsWith('"'))
177+
args = args.Substring(args.IndexOf('"', 1) + 1).TrimStart();
178+
else
179+
args = args.Split(' ', 2).Last();
180+
WriteLine($"{processId,10} {rt,-3} {args}");
181+
}
182+
}
183+
}
141184
}
142185
}

Templates/Script.csx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@ static class Script
4040
public static string ScriptPath { get; } = GetScriptPath();
4141
public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath);
4242
public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath);
43+
4344
public static string EngineAlias { get; } = System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
45+
public static string EnginePath { get; } = "%CSharpScriptRunnerRuntimesDir%" + System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Substring(Environment.GetEnvironmentVariable("CSharpScriptRunnerRuntimesDir").Length);
4446

4547
static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
4648

Templates/ScriptUI.csx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ static class Script
6565
public static string ScriptDirectory { get; } = System.IO.Path.GetDirectoryName(ScriptPath);
6666
public static string ScriptFilename { get; } = System.IO.Path.GetFileName(ScriptPath);
6767
public static string EngineAlias { get; } = System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
68+
public static string EnginePath { get; } = "%CSharpScriptRunnerRuntimesDir%" + System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Substring(Environment.GetEnvironmentVariable("CSharpScriptRunnerRuntimesDir").Length);
6869

6970
static readonly IntPtr _consoleWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
7071

Updates.cs

Lines changed: 0 additions & 62 deletions
This file was deleted.

publish.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
dotnet publish -c Release -r win-x86 -o publish/win/x86 -p:ReleaseTag=dev
22
dotnet publish -c Release -r win-x64 -o publish/win/x64 -p:ReleaseTag=dev
3-
dotnet publish -c Release -o publish/any/any -p:ReleaseTag=dev
3+
# dotnet publish -c Release -o publish/any/any -p:ReleaseTag=dev

0 commit comments

Comments
 (0)