-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathpublish.cs
More file actions
1104 lines (945 loc) · 39.8 KB
/
Copy pathpublish.cs
File metadata and controls
1104 lines (945 loc) · 39.8 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
#:property BuiltInComInteropSupport = true
#:package Microsoft.Extensions.Configuration.Binder@10.0.8
#:package Microsoft.Extensions.Configuration.CommandLine@10.0.8
#:package Polly@8.6.6
#:package SharpSevenZip@2.0.47
#:package System.IO.Hashing@10.0.8
#:package ZstdSharp.Port@0.8.8
#:project src/Starward.Setup.Core/Starward.Setup.Core.csproj
using Microsoft.Extensions.Configuration;
using Polly;
using Polly.Retry;
using SharpSevenZip;
using Starward.Setup.Core;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO.Compression;
using System.IO.Hashing;
using System.Net;
using System.Net.Http.Json;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Serialization;
const string UrlPrefix = "https://starward-static.scighost.com/release";
var knownCommands = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"res",
"compile",
"pack",
"manifest",
"merge",
};
string command = "full";
string[] optionArgs = args;
if (args.Length > 0 && !args[0].StartsWith('-'))
{
if (knownCommands.Contains(args[0]))
{
command = args[0].ToLowerInvariant();
optionArgs = args[1..];
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Error: Unknown subcommand '{args[0]}'. Supported subcommands: res, compile, pack, manifest, merge.");
Console.ResetColor();
return 0;
}
}
var config = new ConfigurationBuilder().AddCommandLine(optionArgs).Build();
if (string.Equals(command, "res", StringComparison.OrdinalIgnoreCase))
{
bool noBuild = config.GetValue<bool>("no-build");
string tag = config.GetValue<string>("tag") ?? DateTimeOffset.UtcNow.ToString("yyyy.MMdd.HHmm");
if (File.Exists("src/Starward.Setup/Assets/Starward.7z"))
{
File.Delete("src/Starward.Setup/Assets/Starward.7z");
}
if (!noBuild)
{
Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + @";C:\Program Files\Microsoft Visual Studio\18\Community\MSBuild\Current\Bin\");
await Process.Start("dotnet", $"publish src/Starward.Setup -o publish/pub_res/ -r win-x64 -p:Version={tag}").EnsureExitSuccessAsync();
File.Move("publish/pub_res/Starward.Setup.exe", $"publish/pub_res/Starward.Setup_x64_{tag}.exe", true);
await Process.Start("dotnet", $"publish src/Starward.Setup -o publish/pub_res/ -r win-arm64 -p:Version={tag}").EnsureExitSuccessAsync();
File.Move("publish/pub_res/Starward.Setup.exe", $"publish/pub_res/Starward.Setup_arm64_{tag}.exe", true);
await Process.Start("msbuild", $"""
src/Starward.Launcher -property:Configuration=Release;Platform=x64;Version={tag};OutDir={Path.GetFullPath("publish/pub_res/")}
""").EnsureExitSuccessAsync();
File.Move("publish/pub_res/Starward.exe", $"publish/pub_res/Starward_x64_{tag}.exe", true);
await Process.Start("msbuild", $"""
src/Starward.Launcher -property:Configuration=Release;Platform=arm64;Version={tag};OutDir={Path.GetFullPath("publish/pub_res/")}
""").EnsureExitSuccessAsync();
File.Move("publish/pub_res/Starward.exe", $"publish/pub_res/Starward_arm64_{tag}.exe", true);
await Process.Start("upx", $"publish/pub_res/Starward.Setup_x64_{tag}.exe").EnsureExitSuccessAsync();
}
var buildRes = new BuildResource
{
Tag = tag,
SetupX64 = new ReleaseSetup
{
FileName = "Starward.Setup.exe",
Size = new FileInfo($"publish/pub_res/Starward.Setup_x64_{tag}.exe").Length,
Hash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes($"publish/pub_res/Starward.Setup_x64_{tag}.exe"))),
Url = $"{UrlPrefix}/pub_res/Starward.Setup_x64_{tag}.exe",
},
SetupArm64 = new ReleaseSetup
{
FileName = "Starward.Setup.exe",
Size = new FileInfo($"publish/pub_res/Starward.Setup_arm64_{tag}.exe").Length,
Hash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes($"publish/pub_res/Starward.Setup_arm64_{tag}.exe"))),
Url = $"{UrlPrefix}/pub_res/Starward.Setup_arm64_{tag}.exe",
},
LauncherX64 = new ReleaseSetup
{
FileName = "Starward.exe",
Size = new FileInfo($"publish/pub_res/Starward_x64_{tag}.exe").Length,
Hash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes($"publish/pub_res/Starward_x64_{tag}.exe"))),
Url = $"{UrlPrefix}/pub_res/Starward_x64_{tag}.exe",
},
LauncherArm64 = new ReleaseSetup
{
FileName = "Starward.exe",
Size = new FileInfo($"publish/pub_res/Starward_arm64_{tag}.exe").Length,
Hash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes($"publish/pub_res/Starward_arm64_{tag}.exe"))),
Url = $"{UrlPrefix}/pub_res/Starward_arm64_{tag}.exe",
}
};
byte[] buildResJsonBytes = JsonSerializer.SerializeToUtf8Bytes(buildRes, JsonContext.Default.BuildResource);
await File.WriteAllBytesAsync("publish/pub_res/pub_res.json", buildResJsonBytes);
await File.WriteAllBytesAsync($"publish/pub_res/pub_res_{tag}.json", buildResJsonBytes);
return 0;
}
string? version = config.GetValue<string>("version");
bool rawEnableDiff = config.GetValue<bool>("diff");
string? rawArchOption = config.GetValue<string>("arch");
bool enableDiff = (string.Equals(command, "manifest", StringComparison.OrdinalIgnoreCase)
|| string.Equals(command, "full", StringComparison.OrdinalIgnoreCase))
&& rawEnableDiff;
string? archOption = command switch
{
"compile" or "pack" or "manifest" or "full" => rawArchOption,
_ => null,
};
List<Architecture> targetArchitectures = [];
if (string.IsNullOrWhiteSpace(archOption))
{
targetArchitectures.Add(Architecture.X64);
targetArchitectures.Add(Architecture.Arm64);
}
else
{
if (!TryParseArchitecture(archOption, out Architecture selectedArch))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error: Invalid --arch value. Use x64 or arm64.");
Console.ResetColor();
return 0;
}
targetArchitectures.Add(selectedArch);
}
if (string.IsNullOrWhiteSpace(version))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error: Version is required. Use --version to specify the version.");
Console.ResetColor();
return 0;
}
bool doCompile = false;
bool doPackage = false;
bool doManifest = false;
bool doMerge = false;
switch (command)
{
case "compile":
doCompile = true;
break;
case "pack":
doPackage = true;
break;
case "manifest":
doManifest = true;
break;
case "merge":
doMerge = true;
break;
case "full":
doCompile = true;
doPackage = true;
doManifest = true;
doMerge = true;
break;
default:
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Error: Unsupported execution mode '{command}'.");
Console.ResetColor();
return 0;
}
if (doMerge && !doCompile && !doPackage && !doManifest)
{
await MergeReleaseInfoFilesAsync(version, targetArchitectures);
return 0;
}
if (doCompile)
{
foreach (var arch in targetArchitectures)
{
string archName = arch.ToLower();
string archPath = $"publish/{archName}";
if (Directory.Exists(archPath))
{
Directory.Delete(archPath, true);
}
Console.WriteLine($"Building {archName} release...");
await Process.Start("dotnet", $"publish src/Starward -c Release -r win-{archName} -o {archPath}/Starward/app-{version} -p:Platform={archName} -p:Version={version}").EnsureExitSuccessAsync();
await File.WriteAllTextAsync($"{archPath}/Starward/version.ini", $"version={version}");
}
}
var _client = new BuildClient();
BuildResource? buildResource = null;
if (doPackage || doManifest)
{
buildResource = await _client.PrepareBuildResourceAsync();
}
string hdiffz = string.Empty;
if (doManifest)
{
hdiffz = await _client.GetHdiffzAsync();
}
ConcurrentDictionary<string, (string XXHash, string SHA256, string CompressedHash)> _hashCache = new();
var release_info = new ReleaseInfo
{
Version = version,
Releases = new(),
};
foreach (var arch in targetArchitectures)
{
if (Directory.Exists($"publish/{arch.ToLower()}"))
{
await CreatePackageAsync(version, arch, InstallType.Setup, release_info, enableDiff, doPackage, doManifest);
await CreatePackageAsync(version, arch, InstallType.Portable, release_info, enableDiff, doPackage, doManifest);
}
}
if (doManifest)
{
await WritePartialReleaseInfoFilesAsync(version, targetArchitectures, release_info);
if (doMerge)
{
await MergeReleaseInfoFilesAsync(version, targetArchitectures);
}
}
return 0;
async Task CreatePackageAsync(string version, Architecture arch, InstallType type, ReleaseInfo release_info, bool enableDiff, bool doPackage, bool doManifest)
{
Console.WriteLine($"Creating package for ({version}, {arch}, {type})...");
string rootPath = type is InstallType.Setup ? $"publish/{arch.ToLower()}/Starward/app-{version}/" : $"publish/{arch.ToLower()}/Starward/";
// compress
if (doPackage)
{
Directory.CreateDirectory("publish/release/package/");
Directory.CreateDirectory("src/Starward.Setup/Assets/");
var compressor = new SharpSevenZipCompressor { CompressionLevel = SharpSevenZip.CompressionLevel.Ultra };
if (type is InstallType.Setup)
{
Console.WriteLine("Compressing setup package...");
File.Copy($"publish/pub_res/Starward.Setup_{arch.ToLower()}.exe", Path.Join(rootPath, "Starward.Setup.exe"), true);
compressor.CompressDirectory(rootPath, "src/Starward.Setup/Assets/Starward.7z");
Console.WriteLine("Creating setup executable...");
var p = Process.Start("dotnet", $"""
publish src/Starward.Setup -o publish/{arch.ToLower()}-setup/ -r win-{arch.ToLower()} -p:Version={version}
""");
await p.WaitForExitAsync();
if (p.ExitCode != 0)
{
throw new Exception($"Publish setup exited with code {p.ExitCode}");
}
File.Move($"publish/{arch.ToLower()}-setup/Starward.Setup.exe", $"publish/release/package/Starward_Setup_{version}_{arch.ToLower()}.exe", true);
File.Delete("src/Starward.Setup/Assets/Starward.7z");
File.Delete(Path.Join(rootPath, "Starward.Setup.exe"));
}
else
{
Console.WriteLine("Compressing portable package...");
File.Copy($"publish/pub_res/Starward_{arch.ToLower()}.exe", Path.Join(rootPath, "Starward.exe"), true);
compressor.CompressDirectory(Path.GetDirectoryName(rootPath.TrimEnd('/', '\\'))!, $"publish/release/package/Starward_Portable_{version}_{arch.ToLower()}.7z");
}
Console.WriteLine("Compression completed.");
Console.WriteLine("--------------------");
}
if (!doManifest)
{
return;
}
// manifest
List<ReleaseManifest?> manifests = new();
Directory.CreateDirectory("publish/release/file/");
Directory.CreateDirectory("publish/release/manifest/");
manifests.Add(await CreateManifestAsync(arch, type, rootPath, version));
if (enableDiff)
{
var release = await _client.GetReleaseInfoDetailAsync(arch, type, CancellationToken.None);
if (release is not null)
{
bool skipPre = false;
int count = 0;
manifests.Add(await CreateManifestAsync(arch, type, rootPath, version, release.Version));
if (!release.Version.Contains("-"))
{
skipPre = true;
}
foreach (var item in release.Diffs)
{
if (!skipPre && item.Value.DiffVersion.Contains("-"))
{
manifests.Add(await CreateManifestAsync(arch, type, rootPath, version, item.Value.DiffVersion));
count++;
}
if (!item.Value.DiffVersion.Contains("-"))
{
manifests.Add(await CreateManifestAsync(arch, type, rootPath, version, item.Value.DiffVersion));
skipPre = true;
count++;
}
if (count >= 5)
{
break;
}
}
}
}
string packageFileName = type is InstallType.Setup ? $"Starward_Setup_{version}_{arch.ToLower()}.exe" : $"Starward_Portable_{version}_{arch.ToLower()}.7z";
release_info.Releases.Add($"{arch}-{type}".ToLower(), new ReleaseInfoDetail
{
Version = version,
Architecture = arch,
InstallType = type,
BuildTime = DateTimeOffset.UtcNow,
ManifestUrl = $"{UrlPrefix}/manifest/manifest_{version.ToLower()}_{arch.ToLower()}_{type.ToLower()}.json",
PackageUrl = $"{UrlPrefix}/package/{packageFileName}",
PackageSize = new FileInfo($"publish/release/package/{packageFileName}").Length,
PackageHash = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes($"publish/release/package/{packageFileName}"))),
Diffs = manifests.Where(x => x?.DiffVersion != null && x.Architecture == arch && x.InstallType == type)
.Select(x => new ReleaseInfoDiff
{
DiffVersion = x!.DiffVersion!,
DiffSize = x.DiffSize,
ManifestUrl = $"{UrlPrefix}/manifest/manifest_{version}_{arch.ToLower()}_{type.ToLower()}_diff_{x.DiffVersion}.json",
})
.ToDictionary(x => x.DiffVersion),
Setup = type is InstallType.Setup ? (arch is Architecture.X64 ? buildResource!.SetupX64 : buildResource!.SetupArm64) : null,
});
}
async Task<ReleaseManifest?> CreateManifestAsync(Architecture arch, InstallType type, string rootPath, string version, string? diffVersion = null)
{
Console.WriteLine($"Creating manifest for ({version}, {arch}, {type}, {diffVersion})...");
ReleaseManifest manifest = new()
{
Architecture = arch,
InstallType = type,
Version = version,
UrlPrefix = $"{UrlPrefix}/file/",
Files = [],
};
ReleaseManifest? oldManifest = null;
if (!string.IsNullOrWhiteSpace(diffVersion))
{
Console.WriteLine($"Getting diff manifest for version {diffVersion}...");
oldManifest = await _client.GetManifestAsync(diffVersion, arch, type, CancellationToken.None);
if (oldManifest is null)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"Warning: No manifest found for diff version {diffVersion}, skipping diff.");
Console.ResetColor();
Console.WriteLine("--------------------");
return null;
}
}
string[] files = Directory.GetFiles(rootPath, "*", SearchOption.AllDirectories);
Console.WriteLine($"Found {files.Length} files to pack.");
foreach (var item in files)
{
manifest.Files.Add(new ReleaseFile
{
Path = Path.GetRelativePath(rootPath, item),
});
}
Console.ForegroundColor = ConsoleColor.DarkGray;
await Parallel.ForEachAsync(manifest.Files, new ParallelOptions { MaxDegreeOfParallelism = Math.Max(8, Environment.ProcessorCount * 2) }, async (item, _) =>
{
string file = Path.Join(rootPath, item.Path);
string xxhash;
string sha256;
string compressedHash;
string id;
string idPath;
if (!_hashCache.TryGetValue(file, out var cachedHash))
{
byte[] bytes = await File.ReadAllBytesAsync(file);
sha256 = Convert.ToHexStringLower(SHA256.HashData(bytes));
xxhash = Convert.ToHexStringLower(XxHash3.Hash(bytes));
id = $"{xxhash}_{sha256}";
idPath = Path.Join("publish/release/file/", id);
using var zstd = new ZstdSharp.Compressor(17);
byte[] zstdBytes = zstd.Wrap(await File.ReadAllBytesAsync(file)).ToArray();
try
{
await File.WriteAllBytesAsync(idPath, zstdBytes);
}
catch
{
await Task.Delay(3000);
await File.WriteAllBytesAsync(idPath, zstdBytes);
}
compressedHash = Convert.ToHexStringLower(SHA256.HashData(zstdBytes));
_hashCache[file] = (xxhash, sha256, compressedHash);
}
else
{
xxhash = cachedHash.XXHash;
sha256 = cachedHash.SHA256;
compressedHash = cachedHash.CompressedHash;
id = $"{xxhash}_{sha256}";
idPath = Path.Join("publish/release/file/", id);
}
item.Id = id;
item.Size = new FileInfo(file).Length;
item.CompressedSize = new FileInfo(idPath).Length;
item.Hash = sha256;
item.CompressedHash = compressedHash;
// diff
if (oldManifest is not null)
{
if (oldManifest.Files.FirstOrDefault(x => x.Size == item.Size && string.Equals(x.Hash, item.Hash, StringComparison.OrdinalIgnoreCase)) is ReleaseFile oldItem)
{
item.Patch = new ReleaseFilePatch
{
OldPath = oldItem.Path,
OldFileSize = oldItem.Size,
OldFileHash = oldItem.Hash,
};
}
else if (MatchDiffFile(item.Path, oldManifest.Files) is ReleaseFile oldItem2)
{
string oldFilePath = Path.Join("publish/temp/", oldItem2.Id);
await _client.DownloadZstdFileAndCheckHashAsync(oldManifest.UrlPrefix + oldItem2.Id, oldFilePath, oldItem2.Hash);
string diffPath = Path.Combine("publish/temp/", $"diff_{item.Id}_{oldItem2.Id}");
if (!File.Exists(diffPath))
{
var p = Process.Start(new ProcessStartInfo
{
FileName = hdiffz,
Arguments = $"""
"{oldFilePath}" "{file}" "{diffPath}" -c-zstd-17
""",
RedirectStandardOutput = true,
RedirectStandardError = true,
});
if (p is not null)
{
await p.WaitForExitAsync();
if (p.ExitCode != 0)
{
throw new Exception($"hdiffz exited with code {p.ExitCode}: {p.StandardError.ReadToEnd()}");
}
}
}
if (File.Exists(diffPath))
{
long diffSize = new FileInfo(diffPath).Length;
item.Patch = new ReleaseFilePatch
{
Id = diffPath,
OldPath = oldItem2.Path,
OldFileSize = oldItem2.Size,
OldFileHash = oldItem2.Hash,
PatchSize = diffSize,
Length = diffSize,
};
// File.Move(diffPath, Path.Join("publish/release/file/", item.Patch.Id), true);
}
}
}
});
manifest.FileCount = manifest.Files.Count;
manifest.Size = manifest.Files.Sum(f => f.Size);
manifest.CompressedSize = manifest.Files.Sum(f => f.CompressedSize);
if (oldManifest is not null)
{
manifest.DiffVersion = oldManifest.Version;
if (type is InstallType.Setup)
{
manifest.DeleteFiles = oldManifest.Files.Select(x => x.Path).Except(manifest.Files.Select(f => f.Path)).ToList();
}
var packages = PackDiffFiles(manifest.Files);
foreach (var package in packages)
{
using var ms = new MemoryStream(package.Size > int.MaxValue ? 0 : (int)package.Size);
long offset = 0;
foreach (var file in package.Files)
{
string diffFilePath = file.Patch!.Id!; // 原id是路径
byte[] diffBytes = await File.ReadAllBytesAsync(diffFilePath);
file.Patch.Offset = offset;
file.Patch.Length = diffBytes.Length;
ms.Write(diffBytes);
offset += diffBytes.Length;
}
byte[] packageBytes = ms.ToArray();
string packageSha256 = Convert.ToHexStringLower(SHA256.HashData(packageBytes));
string packageId = $"{Convert.ToHexStringLower(XxHash3.Hash(packageBytes))}_{packageSha256}";
string packagePath = Path.Join("publish/release/file/", packageId);
await File.WriteAllBytesAsync(packagePath, packageBytes);
foreach (var file in package.Files)
{
file.Patch!.Id = packageId;
file.Patch.PatchSize = packageBytes.LongLength;
file.Patch.PatchHash = packageSha256;
}
}
manifest.DiffFileCount = manifest.Files.Count(f => f.Patch == null) + packages.Count;
manifest.DiffSize = manifest.Files.Where(x => x.Patch == null).Sum(x => x.CompressedSize) + packages.Sum(p => p.Size);
}
byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(manifest, JsonContext.Default.ReleaseManifest);
string manifestName = $"manifest_{version}_{arch}_{type}{(oldManifest is null ? "" : $"_diff_{oldManifest.Version}")}.json";
await File.WriteAllBytesAsync(Path.Join("publish/release/manifest/", manifestName.ToLower()), jsonBytes);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Compressed {manifest.FileCount} files. Total size: {manifest.Size / 1024.0:N2} KB -> {manifest.CompressedSize / 1024.0:N2} KB");
Console.ResetColor();
Console.WriteLine("--------------------");
return manifest;
}
static List<(List<ReleaseFile> Files, long Size)> PackDiffFiles(IEnumerable<ReleaseFile> files)
{
const long TargetPackageSize = 2 * 1024 * 1024; // 2MB
const long MinPackageSize = 18 * 1024 * 1024 / 10; // 1.8MB
const long MaxPackageSize = 22 * 1024 * 1024 / 10; // 2.2MB
List<ReleaseFile> orderedFiles = files
.Where(x => x.Patch?.Id is not null)
.OrderByDescending(x => x.Patch!.Length)
.ThenBy(x => x.Path, StringComparer.Ordinal)
.ToList();
var oversizedPackages = new List<(List<ReleaseFile> Files, long Size)>();
var normalFiles = new List<ReleaseFile>();
foreach (var file in orderedFiles)
{
long fileSize = file.Patch!.Length;
if (fileSize >= MaxPackageSize)
{
oversizedPackages.Add((new List<ReleaseFile> { file }, fileSize));
}
else
{
normalFiles.Add(file);
}
}
long totalNormalSize = normalFiles.Sum(x => x.Patch!.Length);
int initialBinCount = totalNormalSize == 0 ? 0 : (int)Math.Ceiling((double)totalNormalSize / MaxPackageSize);
var packages = new List<(List<ReleaseFile> Files, long Size)>();
for (int i = 0; i < initialBinCount; i++)
{
packages.Add((new List<ReleaseFile>(), 0));
}
foreach (var file in normalFiles)
{
long fileSize = file.Patch!.Length;
int bestPackageIndex = -1;
long bestDistance = long.MaxValue;
long bestSize = long.MinValue;
for (int i = 0; i < packages.Count; i++)
{
long nextSize = packages[i].Size + fileSize;
if (nextSize > MaxPackageSize)
{
continue;
}
long distance = Math.Abs(TargetPackageSize - nextSize);
if (distance < bestDistance || (distance == bestDistance && nextSize > bestSize))
{
bestDistance = distance;
bestSize = nextSize;
bestPackageIndex = i;
}
}
if (bestPackageIndex >= 0)
{
packages[bestPackageIndex].Files.Add(file);
packages[bestPackageIndex] = (packages[bestPackageIndex].Files, packages[bestPackageIndex].Size + fileSize);
}
else
{
packages.Add((new List<ReleaseFile> { file }, fileSize));
}
}
MergeUndersizedPackages(packages, MinPackageSize, TargetPackageSize, MaxPackageSize);
packages.AddRange(oversizedPackages);
packages.RemoveAll(static x => x.Files.Count == 0);
return packages;
}
static void MergeUndersizedPackages(List<(List<ReleaseFile> Files, long Size)> packages, long minPackageSize, long targetPackageSize, long maxPackageSize)
{
while (true)
{
int undersizedIndex = -1;
long undersizedSize = long.MaxValue;
for (int i = 0; i < packages.Count; i++)
{
if (packages[i].Size < minPackageSize && packages[i].Size < undersizedSize)
{
undersizedIndex = i;
undersizedSize = packages[i].Size;
}
}
if (undersizedIndex < 0)
{
return;
}
int mergeIndex = -1;
long bestDistance = long.MaxValue;
long bestMergedSize = long.MinValue;
for (int i = 0; i < packages.Count; i++)
{
if (i == undersizedIndex)
{
continue;
}
long mergedSize = packages[i].Size + undersizedSize;
if (mergedSize > maxPackageSize)
{
continue;
}
long distance = Math.Abs(targetPackageSize - mergedSize);
if (distance < bestDistance || (distance == bestDistance && mergedSize > bestMergedSize))
{
bestDistance = distance;
bestMergedSize = mergedSize;
mergeIndex = i;
}
}
if (mergeIndex < 0)
{
if (!TryBorrowForUndersizedPackage(packages, undersizedIndex, minPackageSize, targetPackageSize, maxPackageSize))
{
return;
}
continue;
}
packages[mergeIndex].Files.AddRange(packages[undersizedIndex].Files);
packages[mergeIndex] = (packages[mergeIndex].Files, packages[mergeIndex].Size + packages[undersizedIndex].Size);
packages.RemoveAt(undersizedIndex);
}
}
static bool TryBorrowForUndersizedPackage(List<(List<ReleaseFile> Files, long Size)> packages, int undersizedIndex, long minPackageSize, long targetPackageSize, long maxPackageSize)
{
int donorIndex = -1;
ReleaseFile? borrowedFile = null;
long bestScore = long.MaxValue;
for (int i = 0; i < packages.Count; i++)
{
if (i == undersizedIndex || packages[i].Files.Count == 0)
{
continue;
}
foreach (var file in packages[i].Files)
{
long fileSize = file.Patch!.Length;
long nextUndersized = packages[undersizedIndex].Size + fileSize;
long nextDonor = packages[i].Size - fileSize;
if (nextUndersized > maxPackageSize)
{
continue;
}
if (nextDonor > 0 && nextDonor < minPackageSize)
{
continue;
}
long score = Math.Abs(targetPackageSize - nextUndersized) + Math.Abs(targetPackageSize - nextDonor);
if (score < bestScore)
{
bestScore = score;
donorIndex = i;
borrowedFile = file;
}
}
}
if (donorIndex < 0 || borrowedFile is null)
{
return false;
}
long borrowedSize = borrowedFile.Patch!.Length;
packages[donorIndex].Files.Remove(borrowedFile);
packages[donorIndex] = (packages[donorIndex].Files, packages[donorIndex].Size - borrowedSize);
packages[undersizedIndex].Files.Add(borrowedFile);
packages[undersizedIndex] = (packages[undersizedIndex].Files, packages[undersizedIndex].Size + borrowedSize);
return true;
}
static ReleaseFile? MatchDiffFile(string newFile, List<ReleaseFile> oldFiles)
{
var fileName = Path.GetFileName(newFile.AsSpan());
int splitCount = newFile.AsSpan().Count(Path.DirectorySeparatorChar);
var span = newFile.AsSpan();
while (true)
{
foreach (var item in oldFiles)
{
var pathSpan = item.Path.AsSpan();
if (pathSpan.EndsWith(span) && pathSpan.Count(Path.DirectorySeparatorChar) == splitCount && Path.GetFileName(pathSpan).SequenceEqual(fileName))
{
return item;
}
}
int index = span.IndexOf(Path.DirectorySeparatorChar);
if (index >= 0)
{
span = span[(index + 1)..];
}
else
{
return null;
}
}
}
async Task WritePartialReleaseInfoFilesAsync(string version, List<Architecture> architectures, ReleaseInfo releaseInfo)
{
Directory.CreateDirectory("publish/release/version/");
foreach (var arch in architectures)
{
string archName = arch.ToLower();
string outputDir = Path.Join("publish/release/version", archName);
Directory.CreateDirectory(outputDir);
ReleaseInfo partial = new()
{
Version = releaseInfo.Version,
Releases = releaseInfo.Releases
.Where(x => x.Value.Architecture == arch)
.ToDictionary(x => x.Key, x => x.Value),
};
byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(partial, JsonContext.Default.ReleaseInfo);
await File.WriteAllBytesAsync(Path.Join(outputDir, $"release_info_{version}.json"), jsonBytes);
File.Copy(Path.Join(outputDir, $"release_info_{version}.json"), Path.Join(outputDir, version), true);
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Release info partial files for version {version} created successfully.");
Console.ResetColor();
}
async Task MergeReleaseInfoFilesAsync(string version, IEnumerable<Architecture> architectures)
{
ReleaseInfo merged = new()
{
Version = version,
Releases = new(),
};
foreach (var arch in architectures.Distinct())
{
string archName = arch.ToLower();
string inputPath = Path.Join("publish/release/version", archName, $"release_info_{version}.json");
if (!File.Exists(inputPath))
{
throw new FileNotFoundException($"Release info file not found: {inputPath}");
}
byte[] jsonBytes = await File.ReadAllBytesAsync(inputPath);
ReleaseInfo partial = JsonSerializer.Deserialize(jsonBytes, JsonContext.Default.ReleaseInfo)
?? throw new Exception($"Failed to read release info: {inputPath}");
foreach (var item in partial.Releases)
{
merged.Releases[item.Key] = item.Value;
}
}
Directory.CreateDirectory("publish/release/version/");
byte[] mergedJsonBytes = JsonSerializer.SerializeToUtf8Bytes(merged, JsonContext.Default.ReleaseInfo);
await File.WriteAllBytesAsync($"publish/release/version/release_info_{version}.json", mergedJsonBytes);
File.Copy($"publish/release/version/release_info_{version}.json", $"publish/release/version/{version}", true);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Release info for version {version} created successfully.");
Console.ResetColor();
}
static bool TryParseArchitecture(string value, out Architecture architecture)
{
architecture = default;
if (string.Equals(value, "x64", StringComparison.OrdinalIgnoreCase))
{
architecture = Architecture.X64;
return true;
}
if (string.Equals(value, "arm64", StringComparison.OrdinalIgnoreCase))
{
architecture = Architecture.Arm64;
return true;
}
return false;
}
public class BuildClient
{
private readonly HttpClient _httpClient;
private readonly ReleaseClient _releaseClient;
private readonly ResiliencePipeline _polly;
public BuildClient()
{
_httpClient = new HttpClient(new SocketsHttpHandler { AutomaticDecompression = DecompressionMethods.All })
{
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher,
};
_httpClient.DefaultRequestHeaders.Add("User-Agent", "Starward Build Tool");
_releaseClient = new ReleaseClient(_httpClient);
_polly = new ResiliencePipelineBuilder().AddRetry(new RetryStrategyOptions
{
MaxRetryAttempts = 3,
BackoffType = DelayBackoffType.Linear,
}).Build();
}
public async Task<BuildResource> PrepareBuildResourceAsync()
{
Console.WriteLine("Preparing build resources...");
BuildResource? res = await _httpClient.GetFromJsonAsync("https://starward-release.scighost.com/release/pub_res/pub_res.json", JsonContext.Default.BuildResource)
?? throw new Exception("Failed to get build resource from server.");
Directory.CreateDirectory("publish/pub_res/");
await DownloadFileAndCheckHashAsync(res.SetupX64.Url, "publish/pub_res/Starward.Setup_x64.exe", res.SetupX64.Hash);
await DownloadFileAndCheckHashAsync(res.SetupArm64.Url, "publish/pub_res/Starward.Setup_arm64.exe", res.SetupArm64.Hash);
await DownloadFileAndCheckHashAsync(res.LauncherX64.Url, "publish/pub_res/Starward_x64.exe", res.LauncherX64.Hash);
await DownloadFileAndCheckHashAsync(res.LauncherArm64.Url, "publish/pub_res/Starward_arm64.exe", res.LauncherArm64.Hash);
return res;
}
public async Task DownloadFileAsync(string url, string path, CancellationToken cancellation = default)
{
await _polly.ExecuteAsync(async token =>
{
using HttpResponseMessage response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);
response.EnsureSuccessStatusCode();
using var hs = await response.Content.ReadAsStreamAsync(token);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
using var fs = File.Create(path);
await hs.CopyToAsync(fs, token);
}, cancellation);
}
public async Task DownloadFileAndCheckHashAsync(string url, string path, string hash, CancellationToken cancellation = default)
{
await _polly.ExecuteAsync(async token =>
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
using var fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
string fileHash = Convert.ToHexStringLower(await SHA256.HashDataAsync(fs, cancellation));
if (string.Equals(fileHash, hash, StringComparison.OrdinalIgnoreCase))
{
return;
}
fs.Position = 0;
using HttpResponseMessage response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);
response.EnsureSuccessStatusCode();
using var hs = await response.Content.ReadAsStreamAsync(token);
await hs.CopyToAsync(fs, token);
fs.SetLength(fs.Position);
fs.Position = 0;
fileHash = Convert.ToHexStringLower(await SHA256.HashDataAsync(fs, cancellation));
if (!string.Equals(fileHash, hash, StringComparison.OrdinalIgnoreCase))
{
throw new Exception($"Hash mismatch for downloaded file. Expected: {hash}, Actual: {fileHash}");
}
}, cancellation);
}
public async Task DownloadZstdFileAndCheckHashAsync(string url, string path, string hash, CancellationToken cancellation = default)
{
await _polly.ExecuteAsync(async token =>
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
using var fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
string fileHash = Convert.ToHexStringLower(await SHA256.HashDataAsync(fs, cancellation));
if (string.Equals(fileHash, hash, StringComparison.OrdinalIgnoreCase))
{
return;
}
fs.Position = 0;
using HttpResponseMessage response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);
response.EnsureSuccessStatusCode();
using var hs = await response.Content.ReadAsStreamAsync(token);
using var zstd = new ZstdSharp.DecompressionStream(hs);
await zstd.CopyToAsync(fs, token);
fs.SetLength(fs.Position);
fs.Position = 0;
fileHash = Convert.ToHexStringLower(await SHA256.HashDataAsync(fs, cancellation));
if (!string.Equals(fileHash, hash, StringComparison.OrdinalIgnoreCase))
{
throw new Exception($"Hash mismatch for downloaded file. Expected: {hash}, Actual: {fileHash}");
}
}, cancellation);
}