-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathStartup.cs
More file actions
4821 lines (4161 loc) · 203 KB
/
Copy pathStartup.cs
File metadata and controls
4821 lines (4161 loc) · 203 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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Funq;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NUglify;
using ServiceStack;
using ServiceStack.IO;
using ServiceStack.Auth;
using ServiceStack.Text;
using ServiceStack.Data;
using ServiceStack.Redis;
using ServiceStack.OrmLite;
using ServiceStack.Configuration;
using ServiceStack.Azure.Storage;
using ServiceStack.Desktop;
using ServiceStack.Html;
using ServiceStack.Logging;
using ServiceStack.NativeTypes.CSharp;
using ServiceStack.Pcl;
using ServiceStack.Script;
namespace Web
{
public class WebAppContext
{
public string Tool { get; set; }
public string[] Arguments { get; set; }
public string AppSettingsPath { get; set; }
public string StartUrl { get; set; }
public string UseUrls { get; set; }
public string IconPath { get; set; }
public string AppDir { get; set; }
public string ToolPath { get; set; }
public string FavIcon { get; set; }
public string RunProcess { get; set; }
public bool DebugMode { get; set; }
public IWebHostBuilder Builder { get; set; }
public IAppSettings AppSettings { get; set; }
public IWebHost Build()
{
AppLoader.Init(AppDir);
return Builder.Build();
}
public string GetDebugString() => new Dictionary<string, object>
{
[nameof(Tool)] = Tool,
[nameof(Arguments)] = Arguments,
[nameof(AppSettingsPath)] = AppSettingsPath,
[nameof(StartUrl)] = StartUrl,
[nameof(UseUrls)] = UseUrls,
[nameof(IconPath)] = IconPath,
[nameof(AppDir)] = AppDir,
[nameof(ToolPath)] = ToolPath,
[nameof(FavIcon)] = FavIcon,
[nameof(RunProcess)] = RunProcess,
[nameof(DebugMode)] = DebugMode,
}.Dump();
}
public delegate void CreateShortcutDelegate(string fileName, string targetPath, string arguments, string workingDirectory, string iconPath);
public class WebAppEvents
{
public CreateShortcutDelegate CreateShortcut { get; set; }
public Action<string> OpenBrowser { get; set; }
public Action<WebAppContext> HandleUnknownCommand { get; set; }
public Action<WebAppContext> RunNetCoreProcess { get; set; }
}
public partial class Startup : ModularStartup
{
public static WebAppEvents Events { get; set; }
public static Func<IAppHost, AppHostInstructions> GetAppHostInstructions { get; set; }
public static string GitHubSource { get; set; } = "sharp-apps Sharp Apps";
public static string GitHubSourceTemplates { get; set; } = "NetCoreTemplates .NET Core C# Templates;NetFrameworkTemplates .NET Framework C# Templates;NetFrameworkCoreTemplates ASP.NET Core Framework Templates";
public static string GistAppsId { get; set; } = "802daba52b6fe6e2ed1430348dc596cb";
public static string GrpcSource { get; set; } = "https://grpc.servicestack.net";
public static List<GistLink> GetGistAppsLinks() => GetGistLinks(GistAppsId, "apps.md");
public static string GetAppsPath(string gistAlias)
{
var homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
return Path.Combine(homeDir, ".sharp-apps", gistAlias);
}
public static string GetGistsAppPath(string gistDir)
{
var homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
return Path.Combine(homeDir, "apps", gistDir);
}
public static bool? DebugMode { get; set; }
public static string[] DebugArgs = CreateArgs("debug", withFlag:'d');
public static string[] ReleaseArgs = CreateArgs("release", withFlag:'c');
public static string[] DescriptionArgs = CreateArgs("desc");
public static string[] IncludeArgs = CreateArgs("include");
public static string[] TargetArgs = CreateArgs("target");
public static string Target { get; set; }
public static string[] ArgumentsArgs = CreateArgs("arguments");
public static string Arguments { get; set; }
public static string[] WorkDirArgs = CreateArgs("workdir");
public static string WorkDir { get; set; }
public static string Description { get; set; }
static string[] TokenArgs = CreateArgs("token");
static string[] PathArgs = CreateArgs("path");
public static string[] QueryArgs = CreateArgs("query", withFlag:'q');
public static NameValueCollection QueryString { get; set; }
public static string[] EvalArgs = CreateArgs("eval", withFlag:'e');
public static string[] LangArgs = CreateArgs("lang");
public static string Lang { get; set; }
public static string[] Includes = { };
public static string PathArg { get; set; }
public static string RunScript { get; set; }
public static bool WatchScript { get; set; }
public static string EvalScript { get; set; }
public static bool GistNew { get; set; }
public static bool GistUpdate { get; set; }
public static bool GistOpen { get; set; }
public static Dictionary<string, object> RunScriptArgs = new();
public static List<string> RunScriptArgV = new();
public static bool Open { get; set; }
public static string ToolFavIcon = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "favicon.ico");
public static GistVirtualFiles GistVfs;
public static Task<Gist> GistVfsTask;
public static Task GistVfsLoadTask;
public static async Task<WebAppContext> CreateWebHost(string tool, string[] args, WebAppEvents events = null)
{
Events = events;
if (args.Length > 0 && args[0] == "mix")
{
await Mix($"{tool} mix", args.Skip(1).ToArray());
return null;
}
var dotnetArgs = new List<string>();
if (!string.IsNullOrEmpty("APP_SOURCE".ToolSetting()))
GitHubSource = "APP_SOURCE".ToolSetting();
if (!string.IsNullOrEmpty("APP_SOURCE_TEMPLATES".ToolSetting()))
GitHubSourceTemplates = "APP_SOURCE_TEMPLATES".ToolSetting();
if (!string.IsNullOrEmpty("APP_SOURCE_GISTS".ToolSetting()))
GistLinksId = "APP_SOURCE_GISTS".ToolSetting();
if (!string.IsNullOrEmpty("APP_SOURCE_APPS".ToolSetting()))
GistAppsId = "APP_SOURCE_APPS".ToolSetting();
if (!string.IsNullOrEmpty("GITHUB_GIST_TOKEN".ToolSetting()))
GitHubToken = "GITHUB_GIST_TOKEN".ToolSetting();
if (!string.IsNullOrEmpty("GITHUB_TOKEN".ToolSetting()))
GitHubToken = "GITHUB_TOKEN".ToolSetting();
if (!string.IsNullOrEmpty("APP_SOURCE_GRPC".ToolSetting()))
GrpcSource = "APP_SOURCE_GRPC".ToolSetting();
InitMix();
var createShortcut = false;
var publish = false;
var copySelf = false;
string copySelfTo = ".";
string createShortcutFor = null;
string runProcess = null;
var runSharpApp = false;
var runLispRepl = false;
var appSettingPaths = new[]
{
"app.settings", "../app/app.settings", "app/app.settings",
};
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.EndsWith(".settings"))
{
appSettingPaths = new[] { arg };
continue;
}
if (arg.EndsWith(".dll") || arg.EndsWith(".exe"))
{
if (Events?.RunNetCoreProcess == null)
throw new NotSupportedException($"This {tool} tool does not support running processes");
runProcess = arg;
continue;
}
if (ProcessFlags(args, arg, ref i))
continue;
if (arg == "shortcut")
{
createShortcut = true;
if (i + 1 < args.Length && (args[i + 1].EndsWith(".dll") || args[i + 1].EndsWith(".exe")))
createShortcutFor = args[++i];
continue;
}
if (arg == "lisp")
{
runLispRepl = runSharpApp = true;
continue;
}
if (EvalArgs.Contains(arg))
{
runSharpApp = true;
if (i + 1 >= args.Length)
{
$"Usage: {tool} -e \"<expression>\"".Print();
return null;
}
EvalScript = args[++i];
if (EvalScript.StartsWith('"') && EvalScript.EndsWith('"'))
EvalScript = (string) JSON.parse(EvalScript);
continue;
}
if (arg == "gist-open" || arg == "open-gist")
{
GistOpen = true;
continue;
}
if (arg == "gist-new")
{
GistNew = true;
continue;
}
if (arg == "gist-update")
{
GistUpdate = true;
continue;
}
if (arg == "publish" || arg == ".publish")
{
publish = true;
continue;
}
if (arg == "--copy-self")
{
copySelf = true;
if (i + 1 < args.Length && !(args[i + 1].StartsWith("-") || args[i + 1].StartsWith("/")))
copySelfTo = args[++i];
var fromDir = Path.GetDirectoryName(typeof(Startup).Assembly.Location);
fromDir.CopyAllTo(copySelfTo);
return null;
}
if (arg is "mix" or "-mix")
{
if (!await Mix($"{tool} mix", new[] {args[++i]}))
return null;
continue;
}
if (arg is "run" or "watch")
{
if (i + 1 >= args.Length)
{
runSharpApp = true;
continue;
}
var script = args[i + 1];
if (script.EndsWith(".settings"))
{
runSharpApp = true;
appSettingPaths = new[] { script };
i++;
continue;
}
if (!(script.EndsWith(".html") || script.EndsWith(".ss") || script.EndsWith(".sc") || script.EndsWith(".l")))
{
// Run SharpApp
string appsDir = GetAppsPath(script);
if (Directory.Exists(appsDir))
{
WebTemplateUtils.AppName = script;
RetryExec(() => Directory.SetCurrentDirectory(appsDir));
runSharpApp = true;
// Run Gist SharpApp
var gistFile = appsDir + ".gist";
if (File.Exists(gistFile))
{
if (Verbose) $"Loading GistVirtualFiles from: {gistFile}".Print();
var gistJson = await File.ReadAllTextAsync(gistFile);
var gist = gistJson.FromJson<Gist>();
GistVfs = new GistVirtualFiles(gist);
GistVfsTask = GistVfs.GetGistAsync(); // fire to load asynchronously
}
i++;
continue;
}
throw new ArgumentException(script.IndexOf('.', StringComparison.Ordinal) >= 0
? "Only .ss. .sc. .l or .html scripts can be run"
: $"No '{script}' App installed");
}
RunScript = script;
WatchScript = arg == "watch";
i += 2; //'run' 'script.ss'
for (; i < args.Length; i++)
{
var key = args[i];
if (key is "mix" or "-mix")
{
if (++i >= args.Length)
throw new Exception($"Usage: {tool} run <name> mix <gist>");
ForceApproval = Silent = true;
if (!await Mix($"{tool} mix", new[] { args[i] }))
return null;
continue;
}
if (ProcessFlags(args, key, ref i))
continue;
RunScriptArgV.Add(key);
if (!(key.FirstCharEquals('-') || key.FirstCharEquals('/')))
continue;
var hasArgValue = i + 1 < args.Length;
RunScriptArgs[key.Substring(1)] = hasArgValue ? args[i + 1] : null;
if (hasArgValue) RunScriptArgV.Add(args[i++ + 1]);
}
continue;
}
if (arg == "open")
{
if (i + 1 >= args.Length)
{
PrintGistLinks(tool, GetGistAppsLinks(), usage:$"Usage: {tool} open <name>");
return null;
}
var target = args[i+1];
for (var j=i+2; j<args.Length; j++)
ProcessFlags(args, args[j], ref j);
RegisterStat(tool, target, "open");
var isGitHubUrl = target.StartsWith("https://gist.github.com/") ||
target.StartsWith("https://github.com/");
if (!isGitHubUrl && !target.IsUrl() && target.IndexOf('/') >= 0)
{
target = "https://github.com/" + target;
isGitHubUrl = true;
}
var gistLinks = !isGitHubUrl ? GetGistAppsLinks() : null;
var gistLink = GetGistAliasLink(target) ?? gistLinks?.FirstOrDefault(x => x.Name == target);
if (!InstallGistApp(tool, target, gistLink, gistLinks, out var appsDir))
return null;
runSharpApp = true;
Open = true;
i += 2; //'open' 'target'
for (; i < args.Length; i++)
{
var key = args[i];
if (key is "mix" or "-mix")
{
if (++i >= args.Length)
throw new Exception($"Usage: {tool} open <name> mix <gist>");
RetryExec(() => Directory.SetCurrentDirectory(appsDir));
ForceApproval = Silent = true;
if (!await Mix($"{tool} mix", new[] { args[i] }))
return null;
continue;
}
if (ProcessFlags(args, key, ref i))
continue;
RunScriptArgV.Add(key);
if (!(key.FirstCharEquals('-') || key.FirstCharEquals('/')))
continue;
var hasArgValue = i + 1 < args.Length;
RunScriptArgs[key.Substring(1)] = hasArgValue ? args[i + 1] : null;
if (hasArgValue) RunScriptArgV.Add(args[i++ + 1]);
}
continue;
}
if (arg is "install" or "i")
{
var gistLinks = GetGistAppsLinks();
if (i + 1 >= args.Length)
{
PrintGistLinks(tool, gistLinks, usage:$"Usage: {tool} open <name>");
return null;
}
var target = args[i+1];
for (var j=i+2; j<args.Length; j++)
ProcessFlags(args, args[j], ref j);
RegisterStat(tool, target, "install");
var isGitHubUrl = target.StartsWith("https://gist.github.com/") ||
target.StartsWith("https://github.com/");
if (!isGitHubUrl && !target.IsUrl() && target.IndexOf('/') >= 0)
{
target = "https://github.com/" + target;
isGitHubUrl = true;
}
if (isGitHubUrl)
{
InstallGistApp(tool, target, null, null, out var appsDir);
return null;
}
var gistLink = GetGistAliasLink(target) ?? gistLinks.FirstOrDefault(x => x.Name == target);
if (gistLink == null)
{
$"No match found for '{target}', available Apps:".Print();
PrintGistLinks(tool, gistLinks, usage:$"Usage: {tool} open <name>");
return null;
}
if (gistLink.GistId != null)
{
if (!InstallGistApp(tool, target, gistLink, gistLinks, out var appsDir))
return null;
var gist = await GistVfsTask;
GistVfsLoadTask = GistVfs.LoadAllTruncatedFilesAsync();
await GistVfsLoadTask;
SerializeGistAppFiles();
$"Gist App Installed, run with:".Print();
$" {tool} run {target}".Print();
return null;
}
if (gistLink.Repo != null)
{
InstallRepo(gistLink.Url.EndsWith(".zip")
? gistLink.Url
: await GitHubUtils.Gateway.GetSourceZipUrlAsync(gistLink.User, gistLink.Repo),
target);
}
"".Print();
$"Installation successful, run with:".Print();
"".Print();
$" {tool} run {target}".Print();
return null;
}
if (arg == "uninstall")
{
if (i + 1 >= args.Length)
{
PrintAppUsage(tool, arg);
return null;
}
var target = args[i + 1];
for (var j=i+2; j<args.Length; j++)
ProcessFlags(args, args[j], ref j);
var installDir = GetAppsPath(target);
var gistFile = installDir + ".gist";
if (!Directory.Exists(installDir) && !File.Exists(gistFile))
{
"".Print();
$"App '{target}' is not installed.".Print();
PrintAppUsage(tool, arg);
return null;
}
if (Directory.Exists(installDir))
DeleteDirectory(installDir);
if (File.Exists(gistFile))
DeleteFile(gistFile);
"".Print();
$"App '{target}' was uninstalled.".Print();
return null;
}
if (arg == "proto-langs")
{
var client = new JsonServiceClient(GrpcSource);
var response = client.Get(new GetLanguages());
"".Print();
$"gRPC Supported Languages:".Print();
"".Print();
var maxKeyLen = response.Results.Max(x => x.Key.Length);
foreach (var kvp in response.Results)
{
$" {kvp.Key.PadRight(maxKeyLen)} {kvp.Value}".Print();
}
"".Print();
"Usage:".Print();
$"{tool} proto-<lang> <url> Add gRPC .proto and generate language".Print();
"".Print();
$"{tool} proto-<lang> <file|dir> Update gRPC .proto and re-gen language".Print();
$"{tool} proto-<lang> Update all gRPC .proto's and re-gen lang".Print();
"".Print();
"Options:".Print();
" --out <dir> Save generated gRPC language sources to <dir>".Print();
return null;
}
if (arg == "alias")
{
var settings = GetGistAliases();
if (i + 1 >= args.Length)
{
var keys = settings.GetAllKeys();
if (keys.Count == 0)
{
"No gist aliases have been defined.".Print();
$"Usage: {tool} alias <alias> <gist-id>".Print();
}
else
{
foreach (var key in keys)
{
var gistId = settings.GetRequiredString(key);
$"{key} {gistId}".Print();
}
}
return null;
}
var target = args[i + 1];
if (i + 2 >= args.Length)
{
settings.GetRequiredString(target).Print();
}
else
{
var gistId = args[i + 2];
if (gistId.StartsWith("https://gist.github.com/"))
gistId = gistId.ToGistId();
if (gistId.Length != 20 && gistId.Length != 32)
{
$"'{args[i + 2]}' is not a valid gist id or URL".Print();
return null;
}
var aliasPath = GetGistAliasesFilePath();
if (settings.Exists(target))
{
var newAliases = new StringBuilder();
foreach (var line in await File.ReadAllLinesAsync(aliasPath))
{
newAliases.AppendLine(line.StartsWith(target + " ") ? $"{target} {gistId}" : line);
}
await File.WriteAllTextAsync(aliasPath, newAliases.ToString());
}
else
{
using var fs = File.AppendText(aliasPath);
await fs.WriteLineAsync($"{target} {gistId}");
}
}
return null;
}
if (arg == "unalias")
{
if (i + 1 >= args.Length)
{
var settings = GetGistAliases();
var keys = settings.GetAllKeys();
if (keys.Count == 0)
{
"No gist aliases have been defined.".Print();
}
else
{
foreach (var key in keys)
{
var gistId = settings.GetRequiredString(key);
$"{key} {gistId}".Print();
}
}
return null;
}
var removeAliases = new List<string>();
for (var j = i + i; j < args.Length; j++)
{
removeAliases.Add(args[j]);
}
var aliasPath = GetGistAliasesFilePath();
var newAliases = new StringBuilder();
foreach (var line in await File.ReadAllLinesAsync(aliasPath))
{
if (removeAliases.Any(x => line.StartsWith(x + " ")))
continue;
newAliases.AppendLine(line);
}
await File.WriteAllTextAsync(aliasPath, newAliases.ToString());
return null;
}
if (arg == "scripts" || arg == "s")
{
var target = i + 1 >= args.Length
? null
: args[i + 1];
if (!File.Exists("package.json"))
{
$"{Path.Combine(Environment.CurrentDirectory,"package.json")} does not exist".Print();
return null;
}
return await RunPackageJsonScript(target);
}
dotnetArgs.Add(arg);
}
if (publish)
{
await PublishToGist(tool);
return null;
}
var allow = new[] { "-h", "-help", "--help", "-v", "-version", "--version", "-location", "--location", "-clear", "--clear", "-clean", "--clean", "-include", "--include" };
var unknownFlag = dotnetArgs.FirstOrDefault(x => x.StartsWith("-") && !allow.Contains(x));
if (unknownFlag != null)
throw new Exception($"Unknown flag: '{unknownFlag}'");
if (Verbose)
{
$"args: '{dotnetArgs.Join(" ")}'".Print();
$"APP_SOURCE={GitHubSource}".Print();
if (runProcess != null)
$"Run Process: {runProcess}".Print();
if (createShortcut)
$"Create Shortcut {createShortcutFor}".Print();
if (GistNew)
$"Command: gist-new".Print();
if (GistUpdate)
$"Command: gist-update".Print();
if (copySelf)
$"Command: publish-exe".Print();
if (RunScript != null)
$"Command: run {RunScript} {RunScriptArgs.ToJsv()}".Print();
if (runLispRepl)
$"Command: LISP REPL".Print();
if (EvalScript != null)
$"Command: eval".Print();
}
if (runProcess != null)
{
RegisterStat(tool, runProcess, "run");
var publishDir = Path.GetDirectoryName(Path.GetFullPath(runProcess)).AssertDirectory();
Events.RunNetCoreProcess(new WebAppContext {
Arguments = dotnetArgs.ToArray(),
RunProcess = runProcess,
AppDir = publishDir,
FavIcon = File.Exists(Path.Combine(publishDir, "favicon.ico"))
? Path.Combine(publishDir, "favicon.ico")
: ToolFavIcon,
});
return null;
}
var instruction = await HandledCommandAsync(tool, dotnetArgs.ToArray());
if (instruction?.Handled == true)
return null;
string appSettingsPath = instruction?.AppSettingsPath;
foreach (var path in appSettingPaths)
{
var fullPath = Path.GetFullPath(path);
if (File.Exists(fullPath))
{
appSettingsPath = fullPath;
break;
}
}
if (!runSharpApp && RunScript == null && dotnetArgs.Count == 0 && appSettingsPath == null && createShortcutFor == null)
{
PrintUsage(tool);
return null;
}
var appDir = appSettingsPath != null
? Path.GetDirectoryName(appSettingsPath)
: createShortcutFor != null
? Path.GetDirectoryName(Path.GetFullPath(createShortcutFor))
: Environment.CurrentDirectory;
var ctx = new WebAppContext
{
Tool = tool,
Arguments = dotnetArgs.ToArray(),
RunProcess = runProcess,
AppSettingsPath = appSettingsPath,
AppSettings = WebTemplateUtils.AppSettings,
AppDir = appDir.AssertDirectory(),
ToolPath = Assembly.GetExecutingAssembly().Location,
DebugMode = DebugMode ?? false,
};
if (instruction == null && dotnetArgs.Count > 0)
{
if (Events?.HandleUnknownCommand != null)
{
Events.HandleUnknownCommand(ctx);
}
else
{
$"Unknown command '{dotnetArgs.Join(" ")}'".Print();
PrintUsage(tool);
}
return null;
}
var appSettingsContent = File.Exists(appSettingsPath)
? await File.ReadAllTextAsync(appSettingsPath)
: null;
if (GistVfsTask != null)
{
var gist = await GistVfsTask;
if (string.IsNullOrEmpty(appSettingsContent))
{
appSettingsContent = gist.Files.TryGetValue("app.settings", out var file)
? (string.IsNullOrEmpty(file.Content) && file.Truncated
? DownloadCachedStringFromUrl(file.Raw_Url)
: file.Content)
: null;
}
// start downloading any truncated gist content whilst AppHost initializes
GistVfsLoadTask = GistVfs.LoadAllTruncatedFilesAsync();
if (string.IsNullOrEmpty(appSettingsContent))
{
appSettingsPath = Path.Combine(appDir, "app.settings");
appSettingsContent = File.Exists(appSettingsPath)
? await File.ReadAllTextAsync(appSettingsPath)
: $"debug false{Environment.NewLine}name {gist.Description ?? "Gist App"}{Environment.NewLine}";
}
}
if (appSettingsContent == null && (appSettingsPath == null && createShortcutFor == null && RunScript == null && !runLispRepl && EvalScript == null))
{
if (Directory.Exists(GetAppsPath("")) && Directory.GetDirectories(GetAppsPath("")).Length > 0)
{
PrintAppUsage(tool, "run");
return null;
}
throw new Exception($"'{appSettingPaths[0]}' does not exist.\n\nView Help: {tool} ?");
}
var usingWebSettings = File.Exists(appSettingsPath);
if (Verbose || (usingWebSettings && !createShortcut && (tool == "x") && instruction == null && appSettingsPath != null))
$"Using '{appSettingsPath}'".Print();
if (appSettingsContent == null && RunScript == null)
{
appSettingsContent = usingWebSettings
? await File.ReadAllTextAsync(appSettingsPath)
: "debug false";
}
var appSettings = appSettingsContent != null
? new DictionarySettings(appSettingsContent.ParseKeyValueText(delimiter:" "))
: new DictionarySettings();
if (RunScript != null)
{
var context = new ScriptContext().Init();
var page = OneTimePage(context, await File.ReadAllTextAsync(RunScript));
if (page.Args.Count > 0)
appSettings = new DictionarySettings(page.Args.ToStringDictionary());
}
// Override any app settings with user app settings
var userAppSettingsPath = AppSettingsUtils.GetUserAppSettingsPath(WebTemplateUtils.AppName);
if (userAppSettingsPath != null && File.Exists(userAppSettingsPath))
{
var userAppSettings = (await File.ReadAllTextAsync(userAppSettingsPath)).ParseKeyValueText(delimiter: " ");
foreach (var setting in userAppSettings)
{
appSettings.Set(setting.Key, setting.Value);
}
}
WebTemplateUtils.AppSettings = new MultiAppSettings(
appSettings,
new EnvironmentVariableSettings());
var bind = "bind".GetAppSetting("localhost");
var ssl = "ssl".GetAppSetting(defaultValue: false);
var port = "port".GetAppSetting(defaultValue: ssl ? "5001-" : "5000-");
if (port.IndexOf('-') >= 0)
{
var startPort = int.TryParse(port.LeftPart('-'), out var val) ? val : 5000;
var endPort = int.TryParse(port.RightPart('-'), out val) ? val : 65535;
port = HostContext.FindFreeTcpPort(startPort, endPort).ToString();
}
var scheme = ssl ? "https" : "http";
var useUrls = "ASPNETCORE_URLS".ToolSetting() ?? $"{scheme}://{bind}:{port}/";
ctx.UseUrls = useUrls;
ctx.StartUrl = useUrls.Replace("://*", "://localhost");
ctx.DebugMode = GetDebugMode();
ctx.FavIcon = GetIconPath(appDir);
if (createShortcut || instruction?.Command == "shortcut")
{
if (instruction?.Command != "shortcut")
RegisterStat(tool, createShortcutFor, "shortcut");
var shortcutPath = createShortcutFor == null
? Path.Combine(appDir, "name".GetAppSetting(defaultValue: "Sharp App"))
: Path.GetFullPath(createShortcutFor.LastLeftPart('.'));
var toolPath = ctx.ToolPath;
var arguments = createShortcutFor == null
? $"\"{ctx.AppSettingsPath}\""
: $"\"{createShortcutFor}\"";
var targetPath = toolPath;
if (toolPath.EndsWith(".dll"))
{
targetPath = "dotnet";
arguments = $"{toolPath} {arguments}";
}
var icon = GetIconPath(appDir, createShortcutFor);
if (!string.IsNullOrEmpty(Target))
targetPath = Target.Replace("^%","%");
if (!string.IsNullOrEmpty(Arguments))
arguments = Arguments.Replace("^%","%");
if (!string.IsNullOrEmpty(WorkDir))
appDir = WorkDir.Replace("^%","%");
if (Verbose) $"CreateShortcut: {shortcutPath}, {targetPath}, {arguments}, {appDir}, {icon}".Print();
CreateShortcut(shortcutPath, targetPath, arguments, appDir, icon, ctx);
if (instruction != null && tool == "app")
$"{Environment.NewLine}Shortcut: {new DirectoryInfo(Path.GetDirectoryName(shortcutPath)).Name}{Path.DirectorySeparatorChar}{Path.GetFileName(shortcutPath)}".Print();
return null;
}
if (RunScript != null || runLispRepl || EvalScript != null)
{
void ExecScript(SharpPagesFeature feature)
{
var ErrorPrefix = $"FAILED run {RunScript} [{string.Join(' ', RunScriptArgV)}]:";
var script = File.ReadAllText(RunScript);
var scriptPage = OneTimePage(feature, script);
EvaluateScript(feature, scriptPage, ErrorPrefix);
}
void EvaluateScript(SharpPagesFeature feature, SharpPage page, string errorPrefix)
{
try
{
var pageResult = new PageResult(page) {
Args = {
["ARGV"] = RunScriptArgV.ToArray(),
}
};
RunScriptArgs.Each(entry => pageResult.Args[entry.Key] = entry.Value);
var output = pageResult.RenderToStringAsync().Result;
output.Print();
if (!Silent && pageResult.LastFilterError != null)
{
errorPrefix.Print();
pageResult.LastFilterStackTrace.Map(x => " at " + x)
.Join(Environment.NewLine).Print();
"".Print();
pageResult.LastFilterError.Message.Print();
pageResult.LastFilterError.ToString().Print();
}
}
catch (Exception ex)
{
ex = ex.UnwrapIfSingleException();
if (ex is StopFilterExecutionException)
{
$"{errorPrefix} {ex.InnerException?.Message}".Print();
return;
}
Verbose = true;
errorPrefix.Print();
throw;
}
}
bool breakLoop = false;
try
{
Console.TreatControlCAsInput = false;
Console.CancelKeyPress += delegate {
// if (Verbose) $"Console.CancelKeyPress".Print();
breakLoop = true;
};
}
catch {} // fails when called from unit test
RegisterStat(tool, RunScript, WatchScript ? "watch" : "run");
var (contentRoot, useWebRoot) = GetDirectoryRoots(ctx);
AppLoader.Init(contentRoot);
var builder = new WebHostBuilder()
.UseFakeServer()
.UseSetting(WebHostDefaults.SuppressStatusMessagesKey, "True")
.UseContentRoot(contentRoot)
.UseWebRoot(useWebRoot)
.ConfigureLogging(config => {
if (!GetDebugMode() && !Verbose &&
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != "Development")
{
config.ClearProviders();
config.SetMinimumLevel(LogLevel.None);
}
})
.UseModularStartup<Startup>();
using (var webHost = builder.Build())
{
var cts = new CancellationTokenSource();