-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBFlatA.cs
1946 lines (1727 loc) · 106 KB
/
BFlatA.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.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Xml.Linq;
[assembly: AssemblyVersion("1.5.0.9"), AssemblyProduct("BFlatA"), AssemblyDescription("https://github.com/xiaoyuvax/bflata")]
namespace BFlatA
{
public enum BuildMode
{
None,
Flat,
Tree,
TreeDepositDependency
}
public enum Verb
{
Script,
Build,
BuildIl,
Flatten,
FlattenAll
}
public static class XExtention
{
public static IEnumerable<XElement> OfInclude(this IEnumerable<XElement> r, string elementName) => r.Where(i => i.Name.LocalName.Equals(elementName, StringComparison.InvariantCultureIgnoreCase) && i.Attribute("Include") != null);
public static IEnumerable<XElement> OfRemove(this IEnumerable<XElement> r, string elementName) => r.Where(i => i.Name.LocalName.Equals(elementName, StringComparison.InvariantCultureIgnoreCase) && i.Attribute("Remove") != null);
}
public sealed class BflataEqualityComparer(bool caseSensitive = false, bool argEquality = false) : EqualityComparer<string>
{
private readonly bool _argEquality = argEquality;
private readonly bool _caseSensitive = caseSensitive;
public static string ReplaceArgEvalurationCharWithSpace(string str)
{
str = str.Trim();
if (str.StartsWith(BFlatA.OPTION_CAP_CHAR))
{
var i = str.IndexOf(BFlatA.ARG_EVALUATION_CHAR);
return i > 0 ? str[..i] + ' ' + str[(i + 1)..] : str;
}
else return str;
}
public override bool Equals(string x, string y)
{
if (_argEquality)
{
x = ReplaceArgEvalurationCharWithSpace(x);
y = ReplaceArgEvalurationCharWithSpace(y);
}
return _caseSensitive ? x == y : x.Equals(y, StringComparison.InvariantCultureIgnoreCase);
}
public override int GetHashCode([DisallowNull] string obj)
{
if (_argEquality) obj = ReplaceArgEvalurationCharWithSpace(obj);
return string.GetHashCode(_caseSensitive ? obj : obj.ToLower());
}
}
public class ReferenceInfo
{
public string Aliases;
public string FusionName;
public string HintPath;
public string Name;
public bool Private;
public string SpecificVersion;
}
internal static class BFlatA
{
public const char ARG_EVALUATION_CHAR = ':';
public const string BUIDFILE_NAME = "build.rsp";
public const int COL_WIDTH = 48;
public const int COL_WIDTH_FOR_ARGS = 16;
public const char COMMENT_TAG = '#';
public const string COMPILER = "bflat";
public const string CUSTOM_EXCLU_FILENAME = "packages.exclu";
public const string EXCLU_EXT = "exclu";
public const string LIB_CACHE_FILENAME = "packages.cache";
public const string NUSPEC_CACHE_FILENAME = "nuspecs.cache";
public const char OPTION_CAP_CHAR = '-';
public const string OPTION_SEPARATOR = " -";
public const string OPTION_SEPARATOR_ESCAPED = "~-";
public const string PATH_PLACEHOLDER = "|";
public static readonly string[] AllowedVerbs = ["build", "build-il", "flatten", "flatten-all"];
public static readonly string[] IGNORED_SUBFOLDER_NAMES = ["bin", "obj"];
public static readonly bool IsLinux = Path.DirectorySeparatorChar == '/';
public static readonly string NL = Environment.NewLine;
public static readonly char PathSep = Path.DirectorySeparatorChar;
public static readonly string WorkingPath = Directory.GetCurrentDirectory();
public static readonly XNamespace XSD_NUGETSPEC = "http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd";
public static Verb Action = Verb.Script;
public static string Architecture = "x64"; //better be default to x64
public static Dictionary<string, ArgDefinition> ArgBook = new() {
{ "Verb", new ArgDefinition(shortName: null, longName: ["build", "build-il", "flatten", "flatten-all"], description: "Verbs", isFlag: true, defaultValue: "") },
{ "RootProject", new ArgDefinition(isOptional: false, isFile: true) },
{ "PackageRoot", new ArgDefinition(shortName: ["-pr"], longName: ["--packageroot"], description: "", isOption: true, isDirectory: true, defaultValue: "") },
{ "Home", new ArgDefinition(shortName: ["-h"], longName: ["--home"], description: "指定MSBuild启动目录", isOption: true, isDirectory: true, defaultValue: "") },
{ "ResGen", new ArgDefinition(shortName: [], longName: ["--resgen"], description: "指定ResGen路径", isOption: true, isFile: true, defaultValue: "") },
{ "Linker", new ArgDefinition(shortName: [], longName: ["--linker"], description: "指定链接器路径", isOption: true, isFile: true, defaultValue: "") },
{ "Include", new ArgDefinition(shortName: ["-inc"], longName: ["--include"], description: "包含额外的BFA文件", isOption: true, isFile: true, defaultValue: "") },
{ "PreBuildActions", new ArgDefinition(shortName: ["-pra"], longName: ["--prebuild"], description: "预构建动作", isOption: true, defaultValue: "") },
{ "PostBuildActions", new ArgDefinition(shortName: ["-poa"], longName: ["--postbuild"], description: "后构建动作", isOption: true, defaultValue: "") },
{ "BuildMode", new ArgDefinition(shortName: ["-bm"], longName: ["--buildmode"], description: "构建模式", isOption: true, defaultValue: "") },
{ "Target", new ArgDefinition(shortName: [], longName: ["--target"], description: "输出类型", isOption: true, defaultValue: "") },
{ "Framework", new ArgDefinition(shortName: ["-fx"], longName: ["--framework"], description: "目标框架", isOption: true, defaultValue: "") },
{ "Architecture", new ArgDefinition(shortName: [], longName: ["--arch"], description: "体系结构", isOption: true, defaultValue: "") },
{ "OS", new ArgDefinition(shortName: [], longName: ["--os"], description: "操作系统", isOption: true, defaultValue: "") },
{ "Output", new ArgDefinition(shortName: ["-o"], longName: ["--out"], description: "输出文件", isOption: true, defaultValue: "") },
{ "Verbose", new ArgDefinition(shortName: ["--verbose"], longName: [], description: "启用详细输出", isFlag: true, defaultValue: "") },
{ "ExcludeFx", new ArgDefinition(shortName: ["-xx"], longName: ["--exclufx"], description: "排除运行时路径", isOption: true, isDirectory: true, defaultValue: "") },
{ "DepositLib", new ArgDefinition(shortName: ["-dd"], longName: ["--depdep"], description: "库部署标志", isFlag: true, defaultValue: "") },
};
public static BflataEqualityComparer ArgEqualityComparer = new(false, true);
public static List<string> BFAFiles = [];
public static BuildMode BuildMode = BuildMode.None;
public static List<string> CacheLib = [];
public static List<string> CacheNuspec = [];
public static bool DepositLib = false;
public static string[] HelpArgs = ["-?", "/?", "-h", "--help"];
public static string[] LibExclu = [];
public static string Linker = null;
public static string MSBuildStartupDirectory = Directory.GetCurrentDirectory();
public static string OS = "windows";
public static string OutputFile = null;
public static string OutputType = "Exe";
public static string PackageRoot = null;
public static List<string> ParsedProjectPaths = [];
public static BflataEqualityComparer PathEqualityComparer = new(IsLinux);
public static List<string> PostBuildActions = [];
public static List<string> PreBuildActions = [];
public static string ResGenPath = "C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.8 Tools\\ResGen.exe";
public static Dictionary<string, string> RootMacros = [];
public static string RootProjectFile = null;
public static List<string> RSPLinesToAppend = [];
public static string RuntimePathExclu = null;
public static string TargetFx = null;
public static bool UseExclu = false;
public static bool UseVerbose = false;
private const string ASPNETCORE_APP = "microsoft.aspnetcore.app";
private const string NETCORE_APP = "microsoft.netcore.app";
private const string WINDESKTOP_APP = "microsoft.windowsdesktop.app";
private const string BFA_FILE_EXT = ".bfa";
public static string LibPathSegment { get; } = PathSep + "lib" + PathSep;
public static string OSArchMoniker { get; } = $"{GetOSMoniker(OS)}-{Architecture}";
public static string RootProjectName => Path.GetFileNameWithoutExtension(RootProjectFile);
public static string RootProjectPath => Path.GetDirectoryName(RootProjectFile);
public static string RuntimesPathSegment { get; } = PathSep + "runtimes" + PathSep;
public static bool UseBFA => RootProjectFile.ToLower().EndsWith(BFA_FILE_EXT);
public static bool UseBuild => Action == Verb.Build || Action == Verb.BuildIl;
public static bool UseBuildIL => Action == Verb.BuildIl;
public static bool UseFlatten => Action == Verb.Flatten || Action == Verb.FlattenAll;
public static bool UseFlattenAll => Action == Verb.FlattenAll;
public static bool UseLinker => !string.IsNullOrEmpty(Linker);
public static string AppendScriptBlock(string script, string myScript) => script + (script == null || script.EndsWith('\n') ? "" : NL + NL) + myScript;
public static string ApplyMacros(this string path, Dictionary<string, string> msBuildMacros)
{
foreach (var m in msBuildMacros) path = path.Replace($"$({m.Key})", m.Value);
return path;
}
public static Process Build(string cmd)
{
Console.WriteLine($"- Executing build script: {(cmd.Length > 22 ? cmd[..22] : cmd)}...");
Process buildProc = null;
if (!string.IsNullOrEmpty(cmd))
{
try
{
if (cmd.StartsWith(COMPILER))
{
var paths = Environment.GetEnvironmentVariable("PATH").Split(IsLinux ? ':' : ';') ?? ["./"];
var compilerPath = paths.FirstOrDefault(i => File.Exists(i + PathSep + (IsLinux ? COMPILER : COMPILER + ".exe")));
if (Directory.Exists(compilerPath))
{
buildProc = Process.Start(compilerPath + PathSep + COMPILER, cmd.Remove(0, COMPILER.Length));
}
else Console.WriteLine("Error: " + COMPILER + " doesn't exist in PATH!");
}
else buildProc = Process.Start(cmd);
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
}
else Console.WriteLine($"Error: build script is emtpy!");
return buildProc;
}
public static Dictionary<string, string> CallResGen(string resxFile, string projectName)
{
Dictionary<string, string> resBook = [];
var frmCsFile = resxFile.Replace(".resx", ".cs");
var strongTypeCsFile = resxFile.Replace(".resx", ".designer.cs");
string myNamespace = projectName.Replace(" ", "_");
try
{
var file2Open = File.Exists(frmCsFile) ? frmCsFile : (File.Exists(strongTypeCsFile) ? strongTypeCsFile : null);
if (!string.IsNullOrEmpty(file2Open))
{
using var csReader = new StreamReader(File.OpenRead(file2Open));
while (!csReader.EndOfStream)
{
var line = csReader.ReadLine().Trim().Split(' ');
if (line.Length >= 2 && line[0] == "namespace")
{
myNamespace = line[1];
break;
}
}
}
var targetResourcesFileName = myNamespace + "." + Path.GetFileNameWithoutExtension(resxFile) + ".resources";
var tempDir = Directory.CreateTempSubdirectory().FullName;
var pathToRes = tempDir + PathSep + targetResourcesFileName;
Process.Start(ResGenPath, ["/useSourcePath", resxFile, pathToRes]).WaitForExit();
resBook.TryAdd(Path.GetFullPath(pathToRes), "");
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return resBook;
}
public static bool CopyFile(string src, string dest)
{
src = src.TrimQuotes();
dest = dest.TrimQuotes();
if (File.Exists(src))
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(dest));
File.Copy(src, dest);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
return true;
}
return false;
}
/// <summary>
/// Exclude Exclus and Runtime libs.
/// </summary>
/// <param name="paths"></param>
/// <returns></returns>
public static IEnumerable<string> DoExclude(this IEnumerable<string> paths) => paths
.Where(i => !i.Contains(PathSep + "runtime."))
.Where(i => !LibExclu.Any(x => i.Contains(PathSep + x + PathSep)));
public static int ExecuteCmds(string title, List<string> cmd)
{
Process buildProc = null;
int exitCode = 0;
foreach (var a in cmd)
{
var splitted = a.TrimQuotes().SplitArgsButQuotesAsBarehead().ToArray();
if (splitted.Length > 1)
{
try
{
buildProc = Process.Start(splitted[0], string.Join(' ', splitted[1..]));
buildProc.WaitForExit();
}
catch (Exception ex) { Console.WriteLine($"{ex.Message}"); }
if (buildProc == null) Console.WriteLine($"Error occurred during executing {title}!!");
else Console.WriteLine($"{title} exit code: {buildProc.ExitCode} - [{a}]");
}
else Console.WriteLine($"{title} invalid: {a}!");
if (buildProc != null) exitCode += buildProc.ExitCode;
}
return exitCode;
}
public static IEnumerable<string> ExtractAttributePathValues(this IEnumerable<XElement> x, string attributeName, string refPath, Dictionary<string, string> msBuildMacros)
=> x.SelectMany(i => GetAbsPaths(ApplyMacros(i.Attribute(attributeName)?.Value, msBuildMacros), refPath));
public static string[] ExtractExclu(string path)
{
if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
try
{
Console.WriteLine($"Extracting exclus from: {path}");
return Directory.GetFiles(path, "*.*.dll").Select(i => Path.GetFileNameWithoutExtension(i).ToLower())
.Where(i => i.StartsWith("system.") || i.StartsWith("microsoft.")).ToArray();
}
catch (Exception ex) { Console.WriteLine($"{ex.Message}{NL}"); }
return [];
}
public static int FlattenProject(string projectName, string projectPath, Verb action,
IEnumerable<string> codeBook, IEnumerable<string> libBook,
IEnumerable<string> nativeLibBook, Dictionary<string, string> resBook,
IEnumerable<string> linkerArg, IEnumerable<string> definedConstants, IEnumerable<string> restArgs,
string outputPath = null)
{
codeBook = codeBook.Distinct(PathEqualityComparer);
libBook = libBook.Distinct(PathEqualityComparer);
nativeLibBook = nativeLibBook.Distinct(PathEqualityComparer);
restArgs = restArgs.Distinct(ArgEqualityComparer);
linkerArg = linkerArg.Distinct(ArgEqualityComparer);
definedConstants = definedConstants.Distinct(ArgEqualityComparer);
Console.WriteLine($"Flatten project:{projectName}");
string targetRoot = null;
try
{
targetRoot = Directory.CreateDirectory(outputPath ?? $"{projectName}.flat").FullName;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return -1;
}
string getFlattenedDest(string src) => Path.GetFullPath(targetRoot + PathSep + Path.GetRelativePath(projectPath, src).Replace(".." + PathSep, ""));
List<string> doCopy(IEnumerable<string> book)
{
List<string> localBook = [];
foreach (var f in book.Select(i => Path.GetFullPath(i.Replace(PATH_PLACEHOLDER, MSBuildStartupDirectory))).Order())
{
var dest = getFlattenedDest(f);
if (CopyFile(f, dest)) localBook.Add(dest);
}
return localBook;
}
IEnumerable<string> flatBook = null;
StringBuilder cmd = new();
if (codeBook.Any())
{
flatBook = doCopy(codeBook.Select(i => Path.GetFullPath(i.Replace(PATH_PLACEHOLDER, MSBuildStartupDirectory))));
if (flatBook.Any())
{
cmd.Append(NL);
cmd.AppendJoin(NL, flatBook);
}
Console.WriteLine($"- Copied {flatBook.Count()}/{codeBook.Count()} code files(*.cs)");
}
if (resBook.Count != 0)
{
flatBook = doCopy(resBook.DistinctBy(kv => Path.GetFileName(kv.Key))
.Select(kv => Path.GetFullPath(kv.Key.Replace(PATH_PLACEHOLDER, MSBuildStartupDirectory))).Order());
if (flatBook.Any())
{
cmd.Append(NL + "-res ");
cmd.AppendJoin(NL + "-res ", flatBook);
}
Console.WriteLine($"- Copied {flatBook.Count()}/{resBook.Count} embedded resources(*.resx and other)");
}
if (libBook.Any())
{
var book = libBook.Select(i => Path.GetFullPath(i.Replace(PATH_PLACEHOLDER, MSBuildStartupDirectory))).Order();
flatBook = action == Verb.FlattenAll ? doCopy(book) : book;
if (flatBook.Any())
{
cmd.Append(NL + "-r ");
cmd.AppendJoin(NL + "-r ", flatBook);
}
Console.WriteLine($"- {(action == Verb.FlattenAll ? "Copied" : "Found")} {flatBook.Count()}/{libBook.Count()} dependent libs(*.dll|*.so)");
}
if (nativeLibBook.Any())
{
var book = nativeLibBook.Select(i => Path.GetFullPath(i.Replace(PATH_PLACEHOLDER, MSBuildStartupDirectory))).Order();
flatBook = action == Verb.FlattenAll ? doCopy(book) : book;
if (flatBook.Any())
{
cmd.Append(NL + "--ldflags ");
cmd.AppendJoin(NL + "--ldflags ", flatBook);
}
Console.WriteLine($"- {(action == Verb.FlattenAll ? "Copied" : "Referenced")} {flatBook.Count()}/{nativeLibBook.Count()} dependent native libs(*.lib|*.a)");
}
if (definedConstants.Any())
{
cmd.Append(NL + "-d ");
cmd.AppendJoin(NL + "-d ", definedConstants);
}
if (linkerArg.Any())
{
cmd.Append(NL + "--ldflags ");
cmd.AppendJoin(NL + "--ldflags ", linkerArg);
}
if (restArgs.Any())
{
cmd.Append(NL);
cmd.AppendJoin(NL, restArgs);
}
if (cmd.Length > 0)
{
Console.WriteLine($"Writing '{projectName}.bfa'...");
cmd.Insert(0, $"#Project:[{projectName}], Timestamp:[{DateTime.Now}]{NL}" +
$"#This BFA file is generated to be served to BFlatA(https://github.com/xiaoyuvax/bflata) with -inc:<BFA file> option.");
WriteScript(cmd.ToString(), $"{targetRoot}{PathSep}{projectName}.bfa");
}
else Console.WriteLine($"No dependencies found.");
return 0;
}
public static Dictionary<string, string> FlattenResX(Dictionary<string, string> resBook, string projectName)
{
Dictionary<string, string> myResBook = [];
foreach (var r in resBook)
{
var fullPath = Path.GetFullPath(r.Key.Replace(PATH_PLACEHOLDER, MSBuildStartupDirectory));
if (Path.GetExtension(fullPath) == ".resx") foreach (var kv in CallResGen(fullPath, projectName)) myResBook.TryAdd(kv.Key, kv.Value); //use absPath
else myResBook.TryAdd(r.Key, null); //use relPath
}
return myResBook;
}
public static string GenerateScript(string projectName,
IEnumerable<string> restArgs,
IEnumerable<string> codeBook,
IEnumerable<string> libBook,
IEnumerable<string> nativeLibBook,
IDictionary<string, string> resBook,
BuildMode buildMode,
string packageRoot,
string outputType = "Exe",
bool isDependency = false,
string outputFile = null)
{
restArgs = restArgs.Distinct(ArgEqualityComparer);
codeBook = codeBook.Distinct(PathEqualityComparer);
libBook = libBook.Distinct(PathEqualityComparer);
nativeLibBook = nativeLibBook.Distinct(PathEqualityComparer);
resBook = resBook.DistinctBy(kv => Path.GetFileName(kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value);//TODO: res uniqueness, by path or by name.
Console.WriteLine($"Generating build script for:{projectName}");
StringBuilder cmd = new();
cmd.AppendLine($"#Project:[{projectName}], Timestamp:[{DateTime.Now}]");
cmd.AppendLine($"#This response file is generated by BFlatA(https://github.com/xiaoyuvax/bflata), and is intended to be compiled by BFlat (https://github.com/bflattened/bflat).");
if (buildMode == BuildMode.Tree)
{
if (!HasOption(restArgs, "-o"))
{
if (isDependency)
{
cmd.AppendLine($"-o {projectName}.dll "); //all dependencies will use the ext of ".dll", even it's an exe, the name doesn't matter.
}
else if (!string.IsNullOrEmpty(outputFile))
{
cmd.AppendLine($"-o {outputFile} ");
}
}
if (!string.IsNullOrEmpty(outputType))
{
cmd.AppendLine($"--target {outputType} ");
}
if (restArgs.Any())
{
cmd.AppendLine(string.Join(NL, restArgs)); // arg per line for Response File
Console.WriteLine($"- Found {restArgs.Count()} args to be passed to BFlat.");
}
}
if (codeBook.Any())
{
cmd.AppendJoin(NL, codeBook.Select(i => Path.GetFullPath(i.Replace(PATH_PLACEHOLDER, MSBuildStartupDirectory))).Order());
Console.WriteLine($"- Found {codeBook.Count()} code files(*.cs)");
}
if (libBook.Any())
{
cmd.Append(NL + "-r ");
cmd.AppendJoin(NL + "-r ", libBook.Select(i => Path.GetFullPath(i.Replace(PATH_PLACEHOLDER, packageRoot))).Order());
Console.WriteLine($"- Found {libBook.Count()} dependent libs(*.dll|*.so)");
}
if (nativeLibBook.Any())
{
cmd.Append(NL + "--ldflags ");
cmd.AppendJoin(NL + "--ldflags ", nativeLibBook.Select(i => "\"" + Path.GetFullPath(i.Replace(PATH_PLACEHOLDER, MSBuildStartupDirectory)) + "\"").Order());
Console.WriteLine($"- Found {nativeLibBook.Count()} dependent native libs(*.lib|*.a)");
}
if (resBook.Any())
{
cmd.Append(NL + "-res ");
var distinctRes = resBook.Select(kv => Path.GetFullPath(kv.Key.Replace(PATH_PLACEHOLDER, MSBuildStartupDirectory)) + (string.IsNullOrEmpty(kv.Value) ? "" : "," + kv.Value)).Order();
cmd.AppendJoin(NL + "-res ", distinctRes);
Console.WriteLine($"- Found {distinctRes.Count()} embedded resources(*.resx and other)");
}
if (buildMode != BuildMode.Tree) cmd.Append(NL); //last return at the end of a script;
return cmd.ToString();
}
public static IEnumerable<string> GetAbsPaths(string path, string basePath)
{
if (string.IsNullOrEmpty(path)) return [];
string fullPath = Path.GetFullPath(ToSysPathSep(path), basePath);
string pattern = Path.GetFileName(fullPath);
if (pattern.Contains('*'))
{
fullPath = Path.GetDirectoryName(fullPath);
string[] fileLst = [];
try
{
fileLst = Directory.GetFiles(fullPath, pattern);
foreach (var i in fileLst) Console.Write(i); //Debug:
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return fileLst;
}
else return [fullPath];
}
public static List<string> GetCodeFiles(string path, List<string> removeLst, List<string> includeLst = null, Dictionary<string, string> msBuildMacros = null)
{
List<string> codeFiles = [];
try
{
var files = Directory.GetFiles(ToSysPathSep(path), "*.cs").Except(removeLst)
.Where(i => !IGNORED_SUBFOLDER_NAMES.Any(x => i.Contains(PathSep + x + PathSep)));
if (includeLst != null) files = files.Concat(includeLst);
files = files.Distinct(PathEqualityComparer).ToRefedPaths();
codeFiles.AddRange(files);
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
foreach (var d in Directory.GetDirectories(path).Where(i => !IGNORED_SUBFOLDER_NAMES.Any(j => i.ToLower().EndsWith(j)))) codeFiles.AddRange(GetCodeFiles(d, removeLst));
return codeFiles;
}
public static string GetExt(string outputType = "Exe") => outputType switch
{
"Exe" => IsLinux ? "" : ".exe",
"WinExe" => ".exe",
_ => ".dll"
};
public static string[] GetFrameworkLibs(string frameworkName)
{
var runtimePath = GetFrameworkPath(frameworkName);
if (Directory.Exists(runtimePath)) return Directory.GetFiles(runtimePath, "*.dll");
else return [];
}
public static string GetFrameworkPath(string frameworkName)
{
static string getLibPath(string fxPath) => Directory.Exists(fxPath) ?
Path.GetFullPath(Directory.GetDirectories(fxPath).OrderDescending()
.FirstOrDefault(i => i.Contains($"{PathSep}{TargetFx.Replace("net", "")}")) + RuntimesPathSegment + OSArchMoniker + LibPathSegment + TargetFx)
: null;
if (!string.IsNullOrEmpty(PackageRoot))
{
return getLibPath(Path.GetFullPath(PackageRoot + PathSep + $"{frameworkName}.runtime.{OSArchMoniker}"))
?? getLibPath(Path.GetFullPath(PackageRoot + PathSep + $"{frameworkName}.{OSArchMoniker}"))
?? getLibPath(Directory.GetDirectories(PackageRoot, $"{frameworkName}.runtime.{OSArchMoniker}", SearchOption.AllDirectories).FirstOrDefault())
?? getLibPath(Directory.GetDirectories(PackageRoot, $"{frameworkName}.{OSArchMoniker}", SearchOption.AllDirectories).FirstOrDefault());
}
return null;
}
public static Dictionary<string, string> GetMacros(string projectFile)
{
string projectPath = Path.GetDirectoryName(projectFile);
if (string.IsNullOrEmpty(projectPath)) projectPath = ".";
projectPath = Path.GetFullPath(projectPath);
string projectName = Path.GetFileNameWithoutExtension(projectFile);
return new()
{
{ "MSBuildProjectDirectory",projectPath.TrimPathEnd()},
//{"MSBuildProjectDirectoryNoRoot},
{ "MSBuildProjectExtension",Path.GetExtension(projectFile)},
{ "MSBuildProjectFile",Path.GetFileName(projectFile)},
{ "MSBuildProjectFullPath",projectFile},
{ "MSBuildProjectName",projectName},
{ "MSBuildRuntimeType",TargetFx},
{ "MSBuildThisFile",Path.GetFileName(projectFile)},
{ "MSBuildThisFileDirectory",projectPath.TrimPathEnd() + PathSep},
//{"MSBuildThisFileDirectoryNoRoot},
{ "MSBuildThisFileExtension",Path.GetExtension(projectFile)},
{ "MSBuildThisFileFullPath",projectPath},
{ "MSBuildThisFileName",Path.GetFileNameWithoutExtension(projectFile)},
{"MSBuildStartupDirectory", MSBuildStartupDirectory.TrimPathEnd() },
{"NativeOutputPath", Path.GetFullPath( Path.GetDirectoryName(OutputFile ?? "./.")).TrimPathEnd()+PathSep },
{"TargetName", projectName },
{ "NativeBinaryExt",OutputType.ToLower() switch{ "exe" => IsLinux?"":".exe","winexe"=>".exe", "shared"=> IsLinux?".so":".dll", _=>""} }
};
}
public static string GetOSMoniker(string archArg) => archArg switch { "windows" => "win", "linux" => "linux", _ => "uefi" };
public static bool HasOption(IEnumerable<string> args, string optNameWithCapChar)
{
var optLen = optNameWithCapChar.Length;
return args.Any(i => i.Length > optLen && i[..optLen].Equals(optNameWithCapChar, StringComparison.InvariantCultureIgnoreCase) && (i[optLen] == ARG_EVALUATION_CHAR || i[optLen] == ' '));
}
public static bool IsReadable(string file)
{
if (File.Exists(file))
{
try
{
Thread.Sleep(1000);
using var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
return true;
}
catch { return false; }
}
return false;
}
public static List<string> LoadCache(string fileName)
{
List<string> cache = [];
int count = 0;
try
{
using var st = new StreamReader(File.OpenRead(fileName));
Console.Write($"Items loaded:");
var (Left, Top) = Console.GetCursorPosition();
while (!st.EndOfStream)
{
Console.SetCursorPosition(Left, Top);
var line = st.ReadLine();
if (!string.IsNullOrEmpty(line) && Directory.Exists(line))
{
cache.Add(line);
count++;
Console.Write(count);
}
}
return cache.DoExclude().ToList();
}
catch (Exception e) { Console.WriteLine(e.Message); }
Console.WriteLine("");
return cache;
}
public static void LoadExclu(string excluFile)
{
int count;
List<string> exclude = [];
try
{
if (File.Exists(excluFile))
{
count = 0;
Console.WriteLine($"Exclu file found: .{PathSep}{Path.GetFileName(excluFile)}");
Console.Write($"Exclus loaded:");
(int Left, int Top) = Console.GetCursorPosition();
using var st = new StreamReader(File.OpenRead(excluFile));
while (!st.EndOfStream)
{
var line = st.ReadLine().ToLower();
if (!string.IsNullOrEmpty(line) && !line.StartsWith('#') && !exclude.Contains(line))
{
exclude.Add(line);
count++;
}
Console.SetCursorPosition(Left, Top);
Console.Write(count);
}
LibExclu = [.. exclude];
}
Console.WriteLine(); //NL here
}
catch (Exception e) { Console.WriteLine(e.Message); }
Console.WriteLine("");
}
/// <summary>
/// Match Referenced Packages from LibCache
/// </summary>
/// <param name="allLibPaths"></param>
/// <param name="packageReferences"></param>
/// <param name="packageRoot"></param>
/// <param name="multiTargets"></param>
/// <param name="libBook">Reference of libBook shall not be altered</param>
/// <returns></returns>
public static List<string> MatchPackages(string[] allLibPaths,
Dictionary<string, string> packageReferences,
string packageRoot,
IEnumerable<string> multiTargets = null,
List<string> libBook = null)
{
libBook ??= [];
bool gotit = false;
if (allLibPaths?.Length > 0)
foreach (var package in packageReferences)
{
gotit = false;
// string requiredLibPath = null, compatibleLibPath = null;
IEnumerable<string> matchedPackageOfVerPaths = null;
string actualTarget = null, actualVersion = null, packageNameLo = null, packagePathSegment = null;
packageNameLo = package.Key.ToLower();
packagePathSegment = PathSep + packageNameLo + PathSep;
//Check Exclu first
if (LibExclu.Contains(packageNameLo))
{
if (UseVerbose) Console.WriteLine($"Info: ignore package Exclu:{packageNameLo}");
}
else foreach (var target in multiTargets)
{
matchedPackageOfVerPaths = null;
actualTarget = null;
(int[] loVerReq, int[] hiVerReq) = ParseVersionRange(package.Value);
if (loVerReq.Length == hiVerReq.Length) // can only compare when lengths equal.
{
matchedPackageOfVerPaths = allLibPaths.Where(i =>
{
var splittedPath = new List<string>(i.Split(PathSep));
var idx = splittedPath.IndexOf(packageNameLo);
if (idx >= 0 && idx < splittedPath.Count - 3 && (splittedPath[^1] == target || splittedPath[^1].StartsWith("netstandard")))
return IsInVersionRange(splittedPath[idx + 1], loVerReq, hiVerReq);
else return false;
}).ToArray(); //don't have to DoExclude() here, for allLibPaths r filtered already.
}
//deduplication of libs references (in Flat mode, dependencies may not be compatible among projects, the top version will be kept)
string libPath = null, absLibPath = null;
if (matchedPackageOfVerPaths != null) foreach (var d in matchedPackageOfVerPaths)
{
absLibPath = Path.GetFullPath(d + PathSep + package.Key + ".dll");
//get case-sensitive file path
try
{
absLibPath = Directory.GetFiles(d).FirstOrDefault(i => i.Equals(absLibPath, StringComparison.InvariantCultureIgnoreCase));
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
if (absLibPath == null) //If the lib(.dll) file with the same name of the package does not exist
{
//do anyting? nothing so far...
}
else //If the lib file with the same name of the package exists
{
//In case packageRoot not given.
libPath = string.IsNullOrEmpty(packageRoot) ? absLibPath : absLibPath.Replace(packageRoot, PATH_PLACEHOLDER);
//Package name might be case-insensitive in .csproj file, while path will be case-sensitive on Linux.
var duplicatedPackages = libBook.Where(i => i.Contains(packagePathSegment));
if (duplicatedPackages.Any())
{
//determine newer version by path string order, no matter if libPath is one of duplicatedPackages.
libPath = duplicatedPackages.Concat([libPath])
.OrderByDescending(i => i.Replace("netstandard", "").Replace("net", "").Replace("netcoreapp", "").Replace("netcore", "").Replace(".", "")).First();
foreach (var p in duplicatedPackages.ToArray()) libBook.Remove(p);
libBook.Add(libPath);
}
else libBook.Add(libPath);
gotit = true;
break;
}
}
if (libPath != null) //libPath should be the sole top lib reference in libBook
{
actualTarget = Path.GetFileName(Path.GetDirectoryName(libPath));
var splittedPath = new List<string>(libPath.Split(PathSep));
var idx = splittedPath.IndexOf(packageNameLo);
if (idx > 0) actualVersion = splittedPath[idx + 1]; //special case: microsoft.win32.registry\5.0.0\runtimes\win\lib\netstandard2.0\Microsoft.Win32.Registry.dll
}
//if no target matched from actual path, use 'target' specified by user.
actualTarget ??= target;
List<string> versionRange = [];
if (package.Value.StartsWith('[') && package.Value.EndsWith(']'))
{
(int[] loVer, int[] hiVer) = ParseVersionRange(package.Value);
versionRange.AddRange(CacheNuspec.Select(i => i.Split(PathSep).LastOrDefault()).Where(i => IsInVersionRange(i, loVer, hiVer)).Distinct());
}
else versionRange = [package.Value];
foreach (var v in versionRange)
{
actualVersion ??= v;
//Parse .nuspec file to obtain package dependencies, while libPath doesn't have to exist.
//Note:some package contains no lib, but .neuspec file with reference to other packages.
string packageOfVerPathSegment = packagePathSegment + actualVersion;
string packageOfVerPath = null;
if (gotit)
{
var firstHalf = absLibPath.Split(LibPathSegment).FirstOrDefault();
if (firstHalf.EndsWith(packageOfVerPathSegment)) packageOfVerPath = firstHalf;
}
else if (!LibExclu.Contains(packageNameLo)) packageOfVerPath = CacheNuspec.FirstOrDefault(i => i.EndsWith(packageOfVerPathSegment));
if (!string.IsNullOrEmpty(packageOfVerPath))
{
//search for dependencies in .nuspec file.
var nuspecPath = Path.GetFullPath(packageOfVerPath + PathSep + packageNameLo + ".nuspec"); //nuespec filename is all lower case
if (File.Exists(nuspecPath))
{
using var stream = File.OpenRead(nuspecPath);
var nuspecDoc = XDocument.Load(stream, LoadOptions.PreserveWhitespace);
var nodes = nuspecDoc.Root.Descendants(XSD_NUGETSPEC + "group");
nodes = nodes.FirstOrDefault(g => g.Attribute("targetFramework")?.Value.ToLower().TrimStart('.') == actualTarget)?.Elements();
var myNugetPackages = nodes?.ToDictionary(kv => kv.Attribute("id")?.Value, kv => kv.Attribute("version")?.Value);
if (myNugetPackages?.Count > 0) libBook = MatchPackages(allLibPaths, myNugetPackages, packageRoot, [actualTarget], libBook); //Append Nuget dependencies to libBook
break;
}
else Console.WriteLine($"Warning: nuspecFile not exists, packages dependencies cannot be determined!! {nuspecPath}");
}
else Console.WriteLine($"Warning: package referenced not found!! {packageNameLo} {actualVersion}");
}
//If any dependency found for any target, stop matching other targets in order(the other targets usually r netstandard).
if (gotit) break;
}
}
return libBook;
}
public static string PadLine(string key, string value) => key.PadRight(COL_WIDTH_FOR_ARGS) + value;
public static int[] PadRight(this int[] intArray, int length)
{
if (intArray.Length < length)
{
int[] newArray = new int[length];
Array.Copy(intArray, newArray, intArray.Length);
return newArray;
}
else return intArray;
}
public static List<string> ParseArgs(IEnumerable<string> args, bool reArrange = true)
{
//Parse input args
List<string> restArgs = new(args);
List<string> bfaFiles = [];
if (!args.Any() || args.Any(HelpArgs.Contains))
{
ShowHelp();
restArgs.Clear();
restArgs.Add("?");
}
else
{
// Verbs must present at the first arg.
var verb = restArgs[0].ToLower();
bool verbDetected = false;
if (AllowedVerbs.Contains(verb))
{
Action = verb switch
{
"build" => Verb.Build,
"build-il" => Verb.BuildIl,
"flatten" => Verb.Flatten,
"flatten-all" => Verb.FlattenAll,
_ => Verb.Script
};
verbDetected = true;
restArgs.RemoveAt(0);
}
if ((verbDetected || string.IsNullOrEmpty(RootProjectFile)) && !restArgs[0].StartsWith('-') && File.Exists(restArgs[0])) //input args don't need trimming quotes in path
{
RootProjectFile = restArgs[0];
//Allow .BFA to be built.
if (Path.GetExtension(RootProjectFile).Equals(BFA_FILE_EXT, StringComparison.InvariantCultureIgnoreCase))
{
bfaFiles.Add(RootProjectFile);
}
restArgs.RemoveAt(0);
}
//rearrange restArgs
if (reArrange && restArgs.Count > 0) restArgs = string.Join(' ', restArgs).SplitArgs().ToList();
//process options:
//restArgs r changing through process, must be fixed to an array first.
//process environmental args first:
foreach (var a in restArgs.ToArray())
{
if (TryTakeArg(a, "-h", "--home", restArgs, out string h))
{
h = h.TrimQuotes();
if (Directory.Exists(h)) MSBuildStartupDirectory = Path.GetFullPath(h).TrimPathEnd();
else Console.WriteLine($"Warning: Home path does not exist or is invalid! {h}");
}
}
//Apply macros
if (!string.IsNullOrEmpty(RootProjectFile)) RootMacros = GetMacros(RootProjectFile);
if (RootMacros.Count != 0) restArgs = restArgs.Select(i => i.ApplyMacros(RootMacros)).ToList();
foreach (var a in restArgs.ToArray())
{
if (TryTakeArg(a, "-pr", "--packageroot", restArgs, out string pr))
{
pr = pr.TrimQuotes();
if (Directory.Exists(pr)) PackageRoot = Path.GetFullPath(pr).TrimPathEnd(); //the ending PathSep may cause shell script variable invalid like $PRcommon.log/ after replacement by placeholder @
else Console.WriteLine($"Warning: PacakgeRoot does not exist or is invalid! {pr}");
}
else if (TryTakeArg(a, "", "--resgen", restArgs, out string rg))
{
rg = rg.TrimQuotes();
if (File.Exists(rg))
{
ResGenPath = Path.GetFullPath(rg).TrimPathEnd();
restArgs.Add("--feature:System.Resources.ResourceManager.AllowCustomResourceTypes=true");
restArgs.Add("--feature:System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization=true");
}
else Console.WriteLine($"Warning: Resgen.exe does not exist or is invalid! {rg}");
}
else if (TryTakeArg(a, "", "--linker", restArgs, out string lnk))
{
lnk = lnk.TrimQuotes().TrimPathEnd();
if (File.Exists(lnk))
{
Linker = Path.GetFullPath(lnk);
restArgs.Add("-c"); //suppress BFlat Linker
}
else Console.WriteLine($"Warning: Linker does not exist or is invalid! {lnk}");
}
else if (TryTakeArg(a, "-inc", "--include", restArgs, out string inc) && File.Exists(inc))
{
bfaFiles.Add(inc);
}
else if (TryTakeArg(a, "-pra", "--prebuild", restArgs, out string prb)) PreBuildActions.Add(prb);
else if (TryTakeArg(a, "-poa", "--postbuild", restArgs, out string pob)) PostBuildActions.Add(pob);
else if (TryTakeArg(a, "-bm", "--buildmode", restArgs, out string bm)) BuildMode = ParseBuildMode(bm);
else if (TryTakeArg(a, "", "--target", restArgs, out string t)) OutputType = t;
else if (TryTakeArg(a, "-fx", "--framework", restArgs, out string fx)) TargetFx = fx.ToLower();
else if (TryTakeArg(a, "", "--arch", restArgs, out string ax))
{
Architecture = ax.ToLower();
restArgs.Add($"--arch:{ax}");
}
else if (TryTakeArg(a, "", "--os", restArgs, out string os))
{
OS = os.ToLower();
restArgs.Add($"--os:{os}");
}
else if (TryTakeArg(a, "-o", "--out", restArgs, out string o)) //hijack -o arg of BFlat, and it shall not be passed to dependent project
{
OutputFile = o;
restArgs.Add($"-o:{o}");
}
else if (a.Equals("--verbose", StringComparison.InvariantCultureIgnoreCase))
{
UseVerbose = true;
}
else if (TryTakeArg(a, "-xx", "--exclufx", restArgs, out string xx))
{
xx = xx.TrimQuotes();
if (Directory.Exists(xx)) RuntimePathExclu = Path.GetFullPath(xx).TrimPathEnd();
else Console.WriteLine($"Warning: RuntimePath does not exist or is invalid! {xx}");
}