- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
Latest commit
172 lines (156 loc) · 7.83 KB
/
Copy pathProgram.cs
File metadata and controls
172 lines (156 loc) · 7.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
usingSystem;
usingSystem.Diagnostics;
usingSystem.IO;
usingSystem.Text;
usingSystem.Linq;
usingSystem.Reflection;
usingSystem.Text.Json;
usingSystem.Runtime.InteropServices;
usingMicrosoft.Win32;
usingSystem.Security.Cryptography;
usingSystem.Collections.Generic;
usingSystem.Collections.ObjectModel;
usingSystem.Threading.Tasks;
usingSystem.Threading;
usingMicrosoft.CodeAnalysis.Emit;
usingMicrosoft.CodeAnalysis;
usingMicrosoft.CodeAnalysis.CSharp.Scripting;
usingMicrosoft.CodeAnalysis.Scripting;
usingSystem.Text.RegularExpressions;
usingMicrosoft.CodeAnalysis.Scripting.Hosting;
usingMicrosoft.CodeAnalysis.CSharp;
usingSystem.IO.Compression;
usingSystem.Net.Http;
usingSystem.Net.Http.Headers;
usingMicrosoft.CodeAnalysis.Host.Mef;
usingMicrosoft.CodeAnalysis.Text;
usingMicrosoft.CodeAnalysis.Completion;
namespaceCSharpScriptRunner
{
publicsealedclassScriptGlobals
{
publicstring[]Args{get;}
internalScriptGlobals(string[]args)=>Args=args;
}
staticpartialclassProgram
{
conststringCmdAlias="csx";
staticreadonlystringCachePath=Path.Combine(Path.GetTempPath(),nameof(CSharpScriptRunner));
conststringUpdateRequestUri="https://api.github.com/repos/ArgusMagnus/CSharpScriptRunner/releases/latest";
conststringPowershellUpdateCommand=
@"$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'";
staticclassVerbs
{
publicconststringVersion="--version";
publicconststringInstall="install";
publicconststringUpdate="update";
publicconststringNew="new";
publicconststringClearCache="clear-cache";
publicconststringInitVSCode="init-vscode";
publicconststringListRunning="list-running";
publicconststringRepl="repl";
}
enumErrorCodes
{
OK=0,
GenericError,
ScriptReturnRangeConflict,
UnrecognizedArgument,
ScriptFileDoesNotExist,
ScriptCompilationFailed,
Reserved=0xFF
}
[STAThread]
// Must run on STA thread (for WinForms/WPF support)
staticintMain(string[]args)
{
// return CurrentThreadSynchronizationContext.Run(async () => (int)(await MainAsync(args)));
return(int)MainAsync(args).Result;
}
staticasyncTask<ErrorCodes>MainAsync(string[]args)
{
usingvarsyncCtxScope=newSynchronizationContextScope();
awaitsyncCtxScope.InstallAndYield(newCurrentThreadSynchronizationContext());
Debug.Assert(Thread.CurrentThread.GetApartmentState()==ApartmentState.STA);
usingvarthisProcess=Process.GetCurrentProcess();
vardir=Path.Combine(Path.GetDirectoryName(thisProcess.MainModule.FileName),"running");
Directory.CreateDirectory(dir);
usingvarfile=newFileStream(Path.Combine(dir,thisProcess.Id.ToString()),FileMode.Create,FileAccess.Write,FileShare.Read,512,FileOptions.DeleteOnClose|FileOptions.Asynchronous);
using(varwriter=newStreamWriter(file,null,-1,true))
awaitwriter.WriteAsync(Environment.CommandLine);
Console.WriteLine($"{nameof(CSharpScriptRunner)}, {BuildInfo.ReleaseTag}");
if(args==null||args.Length==0)
{
PrintHelp();
returnErrorCodes.OK;
}
try
{
switch(args[0].ToLowerInvariant())
{
default:returnawaitRunScript(args);
caseVerbs.Version:break;
caseVerbs.Install:awaitInstall(args.Length>1?string.Equals(args[1],"inplace",StringComparison.OrdinalIgnoreCase):false);break;
caseVerbs.Update:awaitUpdate();break;
caseVerbs.New:CreateNew(args.Length>1?args[1]:null);break;
caseVerbs.ClearCache:awaitClearCache();break;
caseVerbs.InitVSCode:InitVSCode();break;
caseVerbs.ListRunning:awaitListRunning();break;
caseVerbs.Repl:DoRepl();break;
}
}
catch(Exceptionex)
{
if(exisAggregateExceptionaggregateException)
ex=aggregateException.InnerException;
WriteLineError(ex.ToString(),ConsoleColor.Red);
returnErrorCodes.GenericError;
}
returnErrorCodes.OK;
}
staticvoidPrintHelp()
{
varexe=Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName);
Console.WriteLine($"Alias: {CmdAlias}, {exe}");
Console.WriteLine($"{CmdAlias} [-r<RT>] ScriptFilePath [args]");
Console.WriteLine($" Executes the specified script.");
Console.WriteLine($" <RT>: 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(varcodeinEnum.GetValues<ErrorCodes>().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.");
}
staticvoidWriteLine(stringline,ConsoleColorcolor=(ConsoleColor)(-1))
{
if((int)color>-1)
Console.ForegroundColor=color;
Console.WriteLine(line);
Console.ResetColor();
}
staticvoidWriteLineError(stringline,ConsoleColorcolor=(ConsoleColor)(-1))
{
if((int)color>-1)
Console.ForegroundColor=color;
Console.Error.WriteLine(line);
Console.ResetColor();
}
}
}