-
Notifications
You must be signed in to change notification settings - Fork 6
/
Startup.Mix.cs
1587 lines (1340 loc) · 62.5 KB
/
Startup.Mix.cs
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.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ServiceStack;
using ServiceStack.Configuration;
using ServiceStack.Script;
using ServiceStack.Text;
namespace Web
{
public partial class Startup
{
public static string AppVersion { get; set; }
public static string GistLinksId { get; set; } = "9b32b03f207a191099137429051ebde8";
public static bool Verbose { get; set; }
public static string[] VerboseArgs = CreateArgs("verbose", withFlag:'v');
public static bool Silent { get; set; }
static string[] QuietArgs = CreateArgs("quiet");
static string[] SourceArgs = CreateArgs("source", withFlag:'s');
public static bool ForceApproval { get; set; }
static string[] ForceArgs = CreateArgs("force", withFlag:'f');
static string[] YesArgs = CreateArgs("yes", withFlag:'y');
static string[] PreserveArgs = CreateArgs("preserve", withFlag:'p');
public static bool IgnoreSslErrors { get; set; }
private static string[] IgnoreSslErrorsArgs = {"/ignore-ssl-errors", "--ignore-ssl-errors"};
static string[] NameArgs = CreateArgs("name");
static string[] UseArgs = CreateArgs("use");
static string[] DeleteArgs = CreateArgs("delete");
static string[] ReplaceArgs = CreateArgs("replace");
static string[] HelpArgs = { "/help", "--help", "-help", "?" };
static string[] OutArgs = CreateArgs("out");
static string[] RawArgs = CreateArgs("raw");
static string[] JsonArgs = CreateArgs("json");
static string[] RemoveArgs = CreateArgs("remove");
static string[] BasicAuthArgs = CreateArgs("basic");
static string[] AuthSecretArgs = CreateArgs("authsecret");
static string[] SsIdArgs = CreateArgs("ss-id");
static string[] SsPidArgs = CreateArgs("ss-pid");
static string[] CookiesArgs = CreateArgs("cookies");
public static string[] CreateArgs(string name, char? withFlag = null) => withFlag != null
? new [] {"/" + withFlag, "-" + withFlag, "/" + name, "-" + name, "--" + name}
: new [] {"/" + name, "-" + name, "--" + name};
public static string OutDir { get; set; }
public static string BasicAuth { get; set; }
public static string AuthSecret { get; set; }
public static string SsId { get; set; }
public static string SsPid { get; set; }
public static string Cookies { get; set; }
public static string Name { get; set; }
public static string Use { get; set; }
public static bool Preserve { get; set; }
public static bool Raw { get; set; }
public static bool Json { get; set; }
public static bool Remove { get; set; }
public static string GitHubToken { get; set; }
public static string Token { get; set; } // only set from -token cmd line argument
public static List<KeyValuePair<string,string>> ReplaceTokens { get; set; } = new List<KeyValuePair<string, string>>();
public static Func<bool> UserInputYesNo { get; set; } = UseConsoleRead;
private static string CamelToKebab(string str) => Regex.Replace((str ?? ""),"([a-z])([A-Z])","$1-$2").ToLower();
public static bool UseConsoleRead()
{
var keyInfo = Console.ReadKey(intercept:true);
return keyInfo.Key == ConsoleKey.Enter || keyInfo.Key == ConsoleKey.Y;
}
public static bool ApproveUserInputRequests() => true;
public static bool DenyUserInputRequests() => false;
public static void InitMix()
{
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("MIX_SOURCE")))
GistLinksId = Environment.GetEnvironmentVariable("MIX_SOURCE");
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GITHUB_TOKEN")))
GitHubToken = Environment.GetEnvironmentVariable("GITHUB_TOKEN");
}
public static string GetVersion() => Assembly.GetEntryAssembly()?
.GetCustomAttribute<AssemblyFileVersionAttribute>()?
.Version.LastLeftPart('.') ?? "0.0.0";
public static Task RegisterStat(string tool, string name, string type = "tool")
{
if (Environment.GetEnvironmentVariable("SERVICESTACK_TELEMETRY_OPTOUT") == "1" ||
Environment.GetEnvironmentVariable("SERVICESTACK_TELEMETRY_OPTOUT") == "true")
return Task.CompletedTask;
try
{
return $"https://account.servicestack.net/stats/{type}/record?name={name}&source={tool}&version={GetVersion()}"
.GetBytesFromUrlAsync(requestFilter:req => req.ApplyRequestFilters());
}
catch { }
return Task.CompletedTask;
}
private static void PrintGistLinks(string tool, List<GistLink> links, string tag = null, string usage = null)
{
"".Print();
var tags = links.Where(x => x.Tags != null).SelectMany(x => x.Tags).Distinct().OrderBy(x => x).ToList();
if (!string.IsNullOrEmpty(tag))
{
links = links.Where(x => x.MatchesTag(tag)).ToList();
var plural = tag.Contains(',') ? "s" : "";
$"Results matching tag{plural} [{tag}]:".Print();
"".Print();
}
var i = 1;
var padName = links.OrderByDescending(x => x.Name.Length).First().Name.Length + 1;
var padTo = (links.OrderByDescending(x => x.To?.Length ?? 0).First().To?.Length ?? 0) + 1;
var padBy = links.OrderByDescending(x => x.User.Length).First().User.Length + 1;
var padDesc = links.OrderByDescending(x => x.Description.Length).First().Description.Length + 1;
foreach (var link in links)
{
var toLabel = link.To != null
? $" to: {link.To.PadRight(padTo, ' ')}"
: "";
$" {i++.ToString().PadLeft(3, ' ')}. {link.Name.PadRight(padName, ' ')} {link.Description.PadRight(padDesc, ' ')}{toLabel} by @{link.User.PadRight(padBy, ' ')} {link.ToTagsString()}"
.Print();
}
"".Print();
if (usage != null)
{
usage.Print();
return;
}
if (tool.EndsWith("mix"))
{
$" Usage: {tool} <name> <name> ...".Print();
"".Print();
$" Search: {tool} [tag] Available tags: {string.Join(", ", tags)}".Print();
"".Print();
$"Advanced: {tool} ?".Print();
}
else
{
$" Usage: {tool} +<name>".Print();
$" {tool} +<name> <UseName>".Print();
"".Print();
var tagSearch = "[tag]";
$"Search: {tool} + {tagSearch.PadRight(Math.Max(padName - 9, 0), ' ')} Available tags: {string.Join(", ", tags)}"
.Print();
}
}
private static readonly ConcurrentDictionary<string, List<GistLink>> GistLinksCache = new();
private static List<GistLink> GetGistApplyLinks() => GetGistLinks(GistLinksId, "mix.md");
private static List<GistLink> GetGistLinks(string gistId, string name)
{
var gistsIndex = GitHubUtils.Gateway.GetGistFiles(gistId)
.FirstOrDefault(x => x.Key == name);
if (gistsIndex.Key == null)
throw new NotSupportedException($"Could not find '{name}' file in gist '{GistLinksId}'");
return GistLinksCache.GetOrAdd(gistId + ":" + name, key => {
var links = GistLink.Parse(gistsIndex.Value);
return links;
});
}
public class GithubRepo
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Homepage { get; set; }
public int Watchers_Count { get; set; }
public int Stargazers_Count { get; set; }
public int Size { get; set; }
public string Full_Name { get; set; }
public DateTime Created_at { get; set; }
public DateTime? Updated_At { get; set; }
public bool Has_Downloads { get; set; }
public bool Fork { get; set; }
public string Url { get; set; } // https://api.github.com/repos/NetCoreWebApps/bare
public string Html_Url { get; set; }
public bool Private { get; set; }
public GithubRepo Parent { get; set; } // only on single result, e.g: /repos/NetCoreWebApps/bare
}
public static async Task<bool> CheckForUpdates(string tool, Task<string> checkUpdatesAndQuit)
{
if (checkUpdatesAndQuit != null)
{
try
{
var xml = await checkUpdatesAndQuit;
var entryPos = xml.IndexOf("<entry>", StringComparison.Ordinal);
if (entryPos >= 0)
{
var idPos = xml.IndexOf("<id>", entryPos, StringComparison.Ordinal);
if (idPos >= 0)
{
var endIdPos = xml.IndexOf("</id>", idPos, StringComparison.Ordinal);
var startIndex = idPos + "<id>".Length;
var url = xml.Substring(startIndex, endIdPos - startIndex);
var version = url.LastRightPart('/');
if (Verbose) $"Latest {tool} version: {version}".Print();
if (GetVersion() != version) {
"".Print();
$"new version available, update with:".Print();
"".Print();
$" dotnet tool update -g {tool}".Print();
}
}
}
}
catch (Exception ex)
{
if (Verbose)
{
$"Failed to download https://www.nuget.org/packages/{tool}/atom.xml:".Print();
ex.ToString().Print();
if (ex is WebException webEx)
{
try
{
var err = await webEx.GetResponseBodyAsync();
err.Print();
}
catch { /*ignore*/ }
}
}
}
return true;
}
return false;
}
private static string[] ResolveGistAliases(string[] gistAliases, List<GistLink> links)
{
var hasNums = gistAliases.Any(x => int.TryParse(x, out _));
if (hasNums)
{
var resolvedAliases = new List<string>();
foreach (var gistAlias in gistAliases)
{
if (!int.TryParse(gistAlias, out var index))
{
resolvedAliases.Add(gistAlias);
continue;
}
if (index <= 0 || index > links.Count)
throw new ArgumentOutOfRangeException($"Invalid Index '{index}'. Valid Range: 1...{links.Count - 1}");
resolvedAliases.Add(links[index - 1].Name);
}
gistAliases = resolvedAliases.ToArray();
}
return gistAliases;
}
public static bool ApplyGists(string tool, string[] gistAliases, string projectName = null)
{
projectName ??= new DirectoryInfo(Environment.CurrentDirectory).Name;
var unhandledGistAliases = new List<string>();
foreach (var gistAlias in gistAliases)
{
var isGistId = IsGistId(gistAlias);
if (isGistId)
{
WriteGistFile($"https://gist.github.com/{gistAlias}", gistAlias, to: OutDir ?? ".", projectName: projectName, getUserApproval: UserInputYesNo);
ForceApproval = true; //If written once user didn't cancel, assume approval for remaining gists
continue;
}
if (gistAlias.StartsWith("https://") || gistAlias.StartsWith("http://"))
{
WriteGistFile(gistAlias, gistAlias, to: OutDir ?? ".", projectName: projectName, getUserApproval: UserInputYesNo);
ForceApproval = true; //If written once user didn't cancel, assume approval for remaining gists
continue;
}
unhandledGistAliases.Add(gistAlias);
}
if (unhandledGistAliases.Count > 0)
{
var links = GetGistApplyLinks();
var localAliases = GetGistAliases();
var unhandledAliases = ResolveGistAliases(unhandledGistAliases.ToArray(), links);
foreach (var gistAlias in unhandledAliases)
{
if (localAliases.Exists(gistAlias))
{
var aliasGistId = localAliases.GetRequiredString(gistAlias);
WriteGistFile($"https://gist.github.com/{aliasGistId}", aliasGistId, to: OutDir ?? ".", projectName: projectName, getUserApproval: UserInputYesNo);
continue;
}
var gistLink = GistLink.Get(links, gistAlias);
if (gistLink == null)
{
$"No match found for '{gistAlias}', available gists:".Print();
PrintGistLinks(tool, links);
return false;
}
WriteGistFile(gistLink.Url, gistAlias, to: OutDir ?? gistLink.To, projectName: projectName, getUserApproval: UserInputYesNo);
ForceApproval = true; //If written once user didn't cancel, assume approval for remaining gists
}
}
return true;
}
private static bool IsGistId(string gistAlias)
{
var testGistId = gistAlias.IndexOfAny(new[] {'-', '.', ':'}) >= 0
? null
: gistAlias.IndexOf('/') >= 0
? gistAlias.RightPart('/').Length == 40
? gistAlias.LeftPart('/')
: null
: gistAlias;
return testGistId != null && (testGistId.Length == 20 || testGistId.Length == 32);
}
public static bool DeleteGists(string tool, string[] gistAliases, string projectName)
{
projectName ??= new DirectoryInfo(Environment.CurrentDirectory).Name;
var links = GetGistApplyLinks();
var localAliases = GetGistAliases();
gistAliases = ResolveGistAliases(gistAliases, links);
var sb = new StringBuilder();
var allResolvedFiles = new List<string>();
foreach (var gistAlias in gistAliases)
{
string to = ".";
string gistId = null;
string gistLinkUrl = null;
Dictionary<string, string> gistFiles = null;
var isGistId = IsGistId(gistAlias);
if (isGistId)
{
gistFiles = GetGistFiles(gistAlias, out gistLinkUrl);
}
else if (gistAlias.StartsWith("https://") || gistAlias.StartsWith("http://"))
{
gistFiles = GetGistFiles(gistAlias, out gistLinkUrl);
}
else
{
var gistLink = GistLink.Get(links, gistAlias);
if (gistLink == null)
{
$"No match found for '{gistAlias}', available gists:".Print();
PrintGistLinks(tool, links);
return false;
}
gistId = gistLink.GistId;
gistLinkUrl = gistLink.Url;
if (gistId.IsUrl())
{
gistLinkUrl = gistId;
gistId = gistLinkUrl.LastRightPart('/');
}
to = gistLink.To;
gistFiles = GetGistFiles(gistLink.GistId, out gistLinkUrl);
}
var alias = !string.IsNullOrEmpty(gistAlias)
? $"'{gistAlias}' "
: "";
var exSuffix = $" required by {alias}{gistLinkUrl}";
var basePath = ResolveBasePath(to, exSuffix);
var resolvedFiles = new List<string>();
foreach (var gistFile in gistFiles)
{
var resolvedFile = ResolveFilePath(gistFile.Key, basePath, projectName, to);
if (!File.Exists(resolvedFile))
{
if (Verbose) $"Skipping deleting non-existent file: {resolvedFile}".Print();
continue;
}
resolvedFiles.Add(resolvedFile);
allResolvedFiles.Add(resolvedFile);
}
if (resolvedFiles.Count > 0)
{
var label = !string.IsNullOrEmpty(gistAlias)
? $"'{gistAlias}' "
: "";
sb.AppendLine();
var plural = resolvedFiles.Count != 1 ? "s" : "";
sb.AppendLine($"Delete {resolvedFiles.Count} file{plural} from {label}{gistLinkUrl}:");
sb.AppendLine();
foreach (var resolvedFile in resolvedFiles)
{
sb.AppendLine(resolvedFile);
}
}
}
if (allResolvedFiles.Count == 0)
{
var gistsList = string.Join(",", gistAliases);
$"Did not find any existing files from '{gistsList}' to delete".Print();
return false;
}
var getUserApproval = UserInputYesNo;
var silentMode = Silent || getUserApproval == null;
if (!silentMode)
{
if (!ForceApproval)
{
sb.AppendLine()
.AppendLine("Proceed? (n/Y):");
sb.ToString().Print();
if (!getUserApproval())
throw new Exception("Operation cancelled by user.");
}
else
{
sb.ToString().Print();
}
"".Print();
$"Deleting {allResolvedFiles.Count} files...".Print();
}
var folders = new HashSet<string>();
foreach (var resolvedFile in allResolvedFiles)
{
DeleteFile(resolvedFile);
folders.Add(Path.GetDirectoryName(resolvedFile));
}
// Delete empty folders that had gist files
var subFoldersFirst = folders.OrderByDescending(x => x);
folders = new HashSet<string>();
foreach (var folder in subFoldersFirst)
{
if (Directory.GetFiles(folder).Length == 0 && Directory.GetDirectories(folder).Length == 0)
{
DeleteDirectory(folder);
}
else
{
folders.Add(folder);
}
}
if (!silentMode)
{
$"Done.".Print();
}
return true;
}
private static string ResolveFilePath(string gistFilePath, string basePath, string projectName, string applyTo)
{
var useFileName = ReplaceMyApp(osPaths(gistFilePath), projectName);
if (useFileName.EndsWith("?"))
useFileName = useFileName.Substring(0, useFileName.Length - 1);
var resolvedFile = Path.GetFullPath(useFileName, osPaths(basePath));
var writesToFolder = gistFilePath.IndexOf('\\') >= 0;
if (applyTo == "$HOST" && writesToFolder && !Directory.Exists(Path.GetDirectoryName(resolvedFile)))
{
// If resolved file doesn't exist for $HOST gists, check current folder for $"{projectName}.Folder\file.ext"
// e.g. $HOST\ServiceModel => .\ProjectName.ServiceModel
var currentBasePath = Environment.CurrentDirectory;
var tryPath = projectName + "." + gistFilePath;
var resolvedPath = ResolveFilePath(tryPath, currentBasePath, projectName, applyTo:".");
if (Directory.Exists(Path.GetDirectoryName(resolvedPath)))
{
if (Verbose) $"Using matching qualified path: {resolvedPath}".Print();
return resolvedPath;
}
}
return resolvedFile;
}
// More resilient impl for .NET Core
public static void DeleteDirectoryRecursive(string path)
{
//modified from https://stackoverflow.com/a/1703799/85785
foreach (var directory in Directory.GetDirectories(path))
{
var files = Directory.GetFiles(directory);
foreach (var file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
}
DeleteDirectoryRecursive(directory);
}
try
{
Directory.Delete(path, true);
}
catch (IOException)
{
Directory.Delete(path, true);
}
catch (UnauthorizedAccessException)
{
Directory.Delete(path, true);
}
}
public static void DeleteDirectory(string dirPath)
{
if (!Directory.Exists(dirPath)) return;
if (Verbose) $"RMDIR: {dirPath}".Print();
try { DeleteDirectoryRecursive(dirPath); } catch (Exception ex) { Print(ex); }
try { Directory.Delete(dirPath); } catch { }
}
public static void DeleteFile(string filePath)
{
if (!File.Exists(filePath)) return;
if (Verbose) $"RM: {filePath}".Print();
try { File.Delete(filePath); } catch (Exception ex) { Print(ex); }
}
public static void Print(Exception ex)
{
if (Verbose) $"ERROR: {ex.Message}".Print();
}
static string ReplaceMyApp(string input, string projectName)
{
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(projectName))
return input;
var condensed = projectName.Replace("_", "");
var projectNameKebab = CamelToKebab(condensed);
var splitPascalCase = condensed.SplitPascalCase();
var ret = input
.Replace("My_App", projectName)
.Replace("MyApp", condensed)
.Replace("My App", splitPascalCase)
.Replace("my-app", projectNameKebab)
.Replace("myapp", condensed.ToLower())
.Replace("my_app", projectName.ToLower());
if (!Env.IsWindows)
ret = ret.Replace("\r", "");
foreach (var replacePair in ReplaceTokens)
{
ret = ret.Replace(replacePair.Key, replacePair.Value);
}
return ret;
}
public static string SanitizeProjectName(string projectName)
{
if (string.IsNullOrEmpty(projectName))
return null;
var sepChars = new[] { ' ', '-', '+', '_' };
if (projectName.IndexOfAny(sepChars) == -1)
return projectName;
var sb = new StringBuilder();
var words = projectName.Split(sepChars);
foreach (var word in words)
{
if (string.IsNullOrEmpty(word))
continue;
sb.Append(char.ToUpper(word[0])).Append(word.Substring(1));
}
return sb.ToString();
}
public static List<string> HostFiles = new() {
"appsettings.json",
"Web.config",
"App.config",
"Startup.cs",
"Program.cs",
"*.csproj",
};
public static string ResolveBasePath(string to, string exSuffix="")
{
if (to == "." || string.IsNullOrEmpty(to))
return Environment.CurrentDirectory;
if (to.IndexOf("..", StringComparison.Ordinal) >= 0)
throw new NotSupportedException($"Invalid location '{to}'{exSuffix}");
if (to.StartsWith("/"))
if (Env.IsWindows)
throw new NotSupportedException($"Cannot write to '{to}' on Windows{exSuffix}");
else
return to;
if (to.IndexOf(":\\", StringComparison.Ordinal) >= 0)
if (!Env.IsWindows)
throw new NotSupportedException($"Cannot write to '{to}'{exSuffix}");
else
return to;
if (to[0] == '$')
{
if (to.StartsWith("$HOST"))
{
foreach (var hostFile in HostFiles)
{
var matchingFiles = Directory.GetFiles(Environment.CurrentDirectory, hostFile, SearchOption.AllDirectories);
if (matchingFiles.Length > 0)
{
var dirName = Path.GetDirectoryName(matchingFiles[0]);
return dirName;
}
}
var hostFiles = string.Join(", ", HostFiles);
throw new NotSupportedException($"Couldn't find host project location containing any of {hostFiles}{exSuffix}");
}
if (to.StartsWith("$HOME"))
return to.Replace("$HOME", Env.IsWindows
? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
: Environment.GetEnvironmentVariable("HOME"));
var folderValues = EnumUtils.GetValues<Environment.SpecialFolder>();
foreach (var specialFolder in folderValues)
{
if (to.StartsWith(specialFolder.ToString()))
return to.Replace("$" + specialFolder,
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
}
}
else
{
if (to.EndsWith("/"))
{
var dirName = to.Substring(0, to.Length - 1);
var matchingDirs = Directory.GetDirectories(Environment.CurrentDirectory, dirName, SearchOption.AllDirectories);
if (matchingDirs.Length == 0)
throw new NotSupportedException($"Unable to find Directory named '{dirName}'{exSuffix}");
return matchingDirs[0];
}
else
{
var matchingFiles = Directory.GetFiles(Environment.CurrentDirectory, to, SearchOption.AllDirectories);
if (matchingFiles.Length == 0)
throw new NotSupportedException($"Unable to find File named '{to}'{exSuffix}");
var dirName = Path.GetDirectoryName(matchingFiles[0]);
return dirName;
}
}
throw new NotSupportedException($"Unknown location '{to}'{exSuffix}");
}
public static string osPaths(string path) => Env.IsWindows
? path.Replace('/', '\\')
: path.Replace('\\', '/');
public static void WriteGistFile(string gistId, string gistAlias, string to, string projectName, Func<bool> getUserApproval = null)
{
projectName = SanitizeProjectName(projectName);
var gistFiles = GetGistFiles(gistId, out var gistLinkUrl);
var resolvedFiles = new List<KeyValuePair<string,string>>();
KeyValuePair<string, string>? initFile = null;
foreach (var gistFile in gistFiles)
{
if (gistFile.Key.IndexOf("..", StringComparison.Ordinal) >= 0)
throw new Exception($"Invalid file name '{gistFile.Key}' from '{gistLinkUrl}'");
var alias = !string.IsNullOrEmpty(gistAlias)
? $"'{gistAlias}' "
: "";
var exSuffix = $" required by {alias}{gistLinkUrl}";
var basePath = ResolveBasePath(to, exSuffix);
try
{
if (gistFile.Key == "_init")
{
initFile = KeyValuePair.Create(gistFile.Key, gistFile.Value);
continue;
}
var resolvedFile = ResolveFilePath(gistFile.Key, basePath, projectName, to);
var noOverride = Preserve || gistFile.Key.EndsWith("?");
if (noOverride && File.Exists(resolvedFile))
{
if (Verbose) $"Skipping existing optional file: {resolvedFile}".Print();
continue;
}
resolvedFiles.Add(KeyValuePair.Create(resolvedFile, ReplaceMyApp(gistFile.Value, projectName)));
}
catch (Exception ex)
{
throw new Exception($"Cannot write file '{gistFile.Key}' from '{gistLinkUrl}': {ex.Message}", ex);
}
}
var label = !string.IsNullOrEmpty(gistAlias) && !gistAlias.IsUrl()
? $"'{gistAlias}' "
: "";
var sb = new StringBuilder();
foreach (var resolvedFile in resolvedFiles)
{
sb.AppendLine(" " + resolvedFile.Key);
}
var silentMode = Silent || getUserApproval == null;
if (!silentMode)
{
var nl = Environment.NewLine;
if (!ForceApproval)
{
sb.Insert(0, $"{nl}Write files from {label}{gistLinkUrl.UrlDecode()} to:{nl}{nl}");
sb.AppendLine()
.AppendLine("Proceed? (n/Y):");
sb.ToString().Print();
if (!getUserApproval())
throw new Exception("Operation cancelled by user.");
}
else
{
sb.Insert(0, $"Writing files from {label}{gistLinkUrl} to:{nl}{nl}");
sb.ToString().Print();
}
}
if (initFile != null)
{
var hostDir = ResolveBasePath(to, $" required by {gistLinkUrl}");
var lines = initFile.Value.Value.ReadLines();
foreach (var line in lines)
{
if (line.TrimStart().StartsWith("#"))
continue;
var cmd = line.Trim();
if (!cmd.StartsWith("nuget") && !cmd.StartsWith("dotnet") &&
!cmd.StartsWith("flutter") && !cmd.StartsWith("dart") &&
!cmd.StartsWith("kamal"))
{
if (Verbose) $"Command '{cmd}' not supported".Print();
continue;
}
if (cmd.StartsWith("nuget") && !(cmd.StartsWith("nuget add") ||
cmd.StartsWith("nuget restore") ||
cmd.StartsWith("nuget update")))
{
if (Verbose) $"Command '{cmd}' not allowed".Print();
continue;
}
if (cmd.StartsWith("dotnet") && !(cmd.StartsWith("dotnet add ") ||
cmd.StartsWith("dotnet restore ") ||
cmd.Equals("dotnet restore")))
{
if (Verbose) $"Command '{cmd}' not allowed".Print();
continue;
}
if (cmd.StartsWith("flutter") && !(cmd.StartsWith("flutter create ")))
{
if (Verbose) $"Command '{cmd}' not allowed".Print();
continue;
}
if (cmd.StartsWith("dart") && !(cmd.StartsWith("dart pub add") ||
cmd.StartsWith("dart pub get")))
{
if (Verbose) $"Command '{cmd}' not allowed".Print();
continue;
}
if (cmd.StartsWith("kamal") && !(cmd.StartsWith("kamal init")))
{
if (Verbose) $"Command '{cmd}' not allowed".Print();
continue;
}
if (cmd.IndexOfAny(new[]{ '"', '\'', '&', ';', '$', '@', '|', '>' }) >= 0)
{
$"Command contains illegal characters, ignoring: '{cmd}'".Print();
continue;
}
if (cmd.StartsWith("nuget"))
{
if (GetExePath("nuget", out var nugetPath))
{
cmd.Print();
var cmdArgs = cmd.RightPart(' ');
cmdArgs = ReplaceMyApp(cmdArgs, projectName);
PipeProcess(nugetPath, cmdArgs, workDir: hostDir);
}
else
{
$"'nuget' not found in PATH, skipping: '{cmd}'".Print();
}
}
else if (cmd.StartsWith("dotnet"))
{
if (GetExePath("dotnet", out var dotnetPath))
{
cmd.Print();
var cmdArgs = cmd.RightPart(' ');
cmdArgs = ReplaceMyApp(cmdArgs, projectName);
PipeProcess(dotnetPath, cmdArgs, workDir: hostDir);
}
else
{
$"'dotnet' not found in PATH, skipping: '{cmd}'".Print();
}
}
else if (cmd.StartsWith("flutter"))
{
var flutterExe = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "flutter.bat"
: "flutter";
if (GetExePath(flutterExe, out var flutterPath))
{
cmd.Print();
var cmdArgs = cmd.RightPart(' ');
cmdArgs = ReplaceMyApp(cmdArgs, projectName.Replace(".","_"));
PipeProcess(flutterPath, cmdArgs, workDir: hostDir);
}
else
{
$"'flutter' not found in PATH, skipping: '{cmd}'".Print();
}
}
else if (cmd.StartsWith("dart"))
{
var dartExe = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "dart.bat"
: "dart";
if (GetExePath(dartExe, out var dartPath))
{
cmd.Print();
var cmdArgs = cmd.RightPart(' ');
cmdArgs = ReplaceMyApp(cmdArgs, projectName.Replace(".","_"));
PipeProcess(dartPath, cmdArgs, workDir: hostDir);
}
else
{
$"'dart' not found in PATH, skipping: '{cmd}'".Print();
}
}
else if (cmd.StartsWith("kamal"))
{
var kamalExe = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "kamal.bat"
: "kamal";
if (GetExePath(kamalExe, out var kamalPath))
{
cmd.Print();
var cmdArgs = cmd.RightPart(' ');
cmdArgs = ReplaceMyApp(cmdArgs, projectName.Replace(".","_"));
PipeProcess(kamalPath, cmdArgs, workDir: hostDir);
}
else
{
$"'kamal' not found in PATH, skipping: '{cmd}'".Print();
}
}
}
}
foreach (var resolvedFile in resolvedFiles)
{
if (resolvedFile.Key == "_init")
continue;
if (Verbose) $"Writing {resolvedFile.Key}...".Print();
var dir = Path.GetDirectoryName(resolvedFile.Key);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
var filePath = resolvedFile.Key;
var fileContents = resolvedFile.Value;
if (filePath.EndsWith("|base64"))
{
try
{
filePath = filePath.LastLeftPart('|');
var fileBytes = Convert.FromBase64String(fileContents);
File.WriteAllBytes(filePath, fileBytes);
}
catch (Exception ex)
{
$"Could not Convert Base64 binary file '{filePath}': {ex.Message}".Print();
throw;
}
}
else
{
File.WriteAllText(filePath, fileContents);
}
if (filePath.EndsWith(".json.patch"))
{
var patchJson = filePath;
var patchTarget = patchJson.LeftPart(".patch");
if (File.Exists(patchTarget))
{
PatchJsonFileAsync(patchTarget, patchJson).Wait();
$"Patching {patchTarget}...".Print();
File.Delete(patchJson);
}
}
}
}
public static async Task PatchJsonFileAsync(string targetFile, string patchFile)
{
if (!File.Exists(targetFile))
await File.WriteAllTextAsync(targetFile, "{}");
var targetJson = await File.ReadAllTextAsync(targetFile);
var patchJson = await File.ReadAllTextAsync(patchFile);
var patchedFile = PatchJson(targetJson, patchJson);
await File.WriteAllTextAsync(targetFile, patchedFile);
}
public static string PatchJson(string targetJson, string patchJson)