-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathProgram.cs
1192 lines (1058 loc) · 49.4 KB
/
Program.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 Microsoft.DotNet.VersionTools.Automation;
using Microsoft.DotNet.VersionTools.BuildManifest;
using NuGet.Packaging;
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.CommandLine;
using System.Formats.Tar;
using System.IO.Compression;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Xml.Linq;
/// <summary>
/// Tool for comparing Microsoft builds with VMR (Virtual Mono Repo) builds.
/// Identifies missing assets, misclassified assets, and assembly version mismatches.
/// </summary>
public class Program
{
/// <summary>
/// Entry point for the build comparison tool.
/// </summary>
/// <param name="args">Command line arguments.</param>
/// <returns>Return code indicating success (0) or failure (non-zero).</returns>
static int Main(string[] args)
{
var vmrManifestPathArgument = new Option<string>("-vmrManifestPath")
{
Description = "Path to the manifest file",
Required = true
};
var vmrAssetBasePathArgument = new Option<string>("-vmrAssetBasePath")
{
Description = "Path to the manifest file",
Required = true
};
var msftAssetBasePathArgument = new Option<string>("-msftAssetBasePath")
{
Description = "Path to the asset base path",
Required = true
};
var issuesReportArgument = new Option<string>("-issuesReport")
{
Description = "Path to output xml file for non-baselined issues.",
Required = true
};
var noIssuesReportArgument = new Option<string>("-noIssuesReport")
{
Description = "Path to output xml file for baselined issues and assets without issues.",
Required = true
};
var parallelismArgument = new Option<int>("-parallel")
{
Description = "Amount of parallelism used while analyzing the builds.",
DefaultValueFactory = _ => 8,
Required = true
};
var baselineArgument = new Option<string>("-baseline")
{
Description = "Path to the baseline build manifest.",
Required = true
};
var rootCommand = new RootCommand(description: "Tool for comparing Microsoft builds with VMR builds.")
{
vmrManifestPathArgument,
vmrAssetBasePathArgument,
msftAssetBasePathArgument,
issuesReportArgument,
noIssuesReportArgument,
baselineArgument,
parallelismArgument
};
rootCommand.Description = "Compares build manifests and outputs missing or misclassified assets.";
var result = rootCommand.Parse(args);
var comparer = new Program(result.GetValue(vmrManifestPathArgument),
result.GetValue(vmrAssetBasePathArgument),
result.GetValue(msftAssetBasePathArgument),
result.GetValue(issuesReportArgument),
result.GetValue(noIssuesReportArgument),
result.GetValue(baselineArgument),
result.GetValue(parallelismArgument));
return (int)comparer.CompareBuilds().GetAwaiter().GetResult();
}
/// <summary>
/// Path to the VMR manifest file.
/// </summary>
private string _vmrManifestPath;
/// <summary>
/// Base path for VMR build assets.
/// </summary>
private string _vmrBuildAssetBasePath;
/// <summary>
/// Base path for Microsoft build assets.
/// </summary>
private string _baseBuildAssetBasePath;
/// <summary>
/// Path where the comparison report for issues will be saved.
/// </summary>
private string _issuesReportPath;
/// <summary>
/// Path where the comparison report for no issues will be saved.
/// </summary>
private string _noIssuesReportPath;
/// <summary>
/// Semaphore used to control parallel processing.
/// </summary>
private SemaphoreSlim _throttle;
/// <summary>
/// Report containing the results of the comparison.
/// </summary>
private ComparisonReport _comparisonReport = new ComparisonReport();
/// <summary>
/// List of all asset mappings between base and VMR builds.
/// </summary>
private List<AssetMapping> _assetMappings = new List<AssetMapping>();
private Baseline _baseline;
/// <summary>
/// Initializes a new instance of the Program class with specified parameters.
/// </summary>
/// <param name="vmrManifestPath">Path to the VMR manifest file.</param>
/// <param name="vmrAssetBasePath">Base path for VMR build assets.</param>
/// <param name="baseBuildAssetBasePath">Base path for Microsoft build assets.</param>
/// <param name="issuesReportPath">Path where the comparison report for issues will be saved.</param>
/// <param name="noIssuesReportPath">Path where the comparison report for no issues will be saved.</param>
/// <param name="baselineFilePath">Path to the baseline build manifest.</param>
/// <param name="parallelTasks">Number of tasks to run in parallel.</param>
private Program(string vmrManifestPath,
string vmrAssetBasePath,
string baseBuildAssetBasePath,
string issuesReportPath,
string noIssuesReportPath,
string baselineFilePath,
int parallelTasks)
{
_vmrManifestPath = vmrManifestPath;
_vmrBuildAssetBasePath = vmrAssetBasePath;
_baseBuildAssetBasePath = baseBuildAssetBasePath;
_issuesReportPath = issuesReportPath;
_noIssuesReportPath = noIssuesReportPath;
_throttle = new SemaphoreSlim(parallelTasks, parallelTasks);
if (!string.IsNullOrEmpty(baselineFilePath))
{
_baseline = new Baseline(baselineFilePath);
}
}
/// <summary>
/// Executes the build comparison process.
/// </summary>
/// <returns>Task representing the asynchronous operation with a return code: 0 for success, 1 for failure.</returns>
private async Task<int> CompareBuilds()
{
try
{
GenerateAssetMappings();
await EvaluateAssets();
ApplyBaselines();
GenerateReport();
return 0;
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.ToString()}");
return 1;
}
}
private void ApplyBaselines()
{
if (_baseline == null)
{
return;
}
Console.WriteLine($"Applying baseline.");
foreach (var mapping in _assetMappings)
{
foreach (var issue in mapping.Issues)
{
issue.Baseline = _baseline.GetMatchingBaselineEntries(issue, mapping).FirstOrDefault();
}
}
}
/// <summary>
/// Evaluates all asset mappings by processing packages and blobs in parallel.
/// </summary>
/// <returns>Task representing the asynchronous operation.</returns>
private async Task EvaluateAssets()
{
var evaluationTasks = _assetMappings.Select(mapping => Task.Run(async () =>
{
await EvaluateAsset(mapping);
}));
await Task.WhenAll(evaluationTasks);
}
/// <summary>
/// Generates asset mappings between base builds and VMR builds.
/// </summary>
/// <remarks>
/// Walks through each repository's merged manifest and maps files between
/// the base build and VMR build based on asset IDs.
/// </remarks>
private void GenerateAssetMappings()
{
Console.WriteLine($"Loading VMR manifest from {_vmrManifestPath}");
// Load the XML file
XDocument vmrMergedManifestContent = XDocument.Load(_vmrManifestPath);
// Get all files in the assets folder, including subfolders
var allFiles = Directory.GetFiles(_baseBuildAssetBasePath, "*", SearchOption.AllDirectories);
// Walk the top-level directories of the asset base path, and find the MergedManifest under each
// one. The MergedManifest.xml contains the list of outputs produced by the repo.
foreach (var baseDirectory in Directory.GetDirectories(_baseBuildAssetBasePath, "*", SearchOption.TopDirectoryOnly))
{
// Find the merged manifest underneath this directory
// (e.g. <assetBasePath>/arcade/nonshipping/<version>>/MergedManifest.xml)
string repoMergedManifestPath = Directory.GetFiles(baseDirectory,
"MergedManifest.xml", SearchOption.AllDirectories)
.FirstOrDefault();
if (repoMergedManifestPath == null)
{
Console.WriteLine($"Failed to find merged manifest for {baseDirectory}");
continue;
}
_assetMappings.AddRange(MapFilesForManifest(vmrMergedManifestContent,
baseDirectory,
_vmrBuildAssetBasePath,
repoMergedManifestPath));
}
}
/// <summary>
/// Generates the final comparison report and saves it to the specified output files.
/// </summary>
private void GenerateReport()
{
// Create two separate reports
var issuesReport = new ComparisonReport();
var noIssuesReport = new ComparisonReport();
// Assets with errors go to the issues report
var assetsWithErrors = _assetMappings
.Where(mapping => mapping.EvaluationErrors.Any())
.ToList();
// Process each asset mapping to potentially split between reports
var assetsForReport = _assetMappings
.Where(mapping => !mapping.EvaluationErrors.Any())
.SelectMany(mapping =>
{
var nonBaselinedIssues = mapping.Issues.Any(i => i.Baseline == null);
var baselinedIssues = mapping.Issues.Any(i => i.Baseline != null);
if (nonBaselinedIssues && baselinedIssues)
{
// If it has both non-baselined and baselined issues, create a copy for the issues report
var nonBaselinedMapping = CloneAssetMappingWithFilteredIssues(mapping, i => i.Baseline == null);
var baselinedMapping = CloneAssetMappingWithFilteredIssues(mapping, i => i.Baseline != null);
return new[] { nonBaselinedMapping, baselinedMapping };
}
else
{
// If it has no issues at all, it goes to the no-issues report as is
return new[] { mapping };
}
})
.ToList();
// Populate the issues report
issuesReport.AssetsWithIssues = assetsForReport
.Where(mapping => mapping.Issues.Any(i => i.Baseline == null))
.OrderByDescending(mapping => mapping.Issues.Count)
.ToList();
issuesReport.AssetsWithErrors = assetsWithErrors;
issuesReport.AssetsWithoutIssues = new List<AssetMapping>();
// Populate the no-issues report
noIssuesReport.AssetsWithIssues = assetsForReport
.Where(mapping => mapping.Issues.All(i => i.Baseline != null))
.ToList();
noIssuesReport.AssetsWithoutIssues = assetsForReport
.Where(mapping => !mapping.Issues.Any())
.ToList();
noIssuesReport.AssetsWithErrors = new List<AssetMapping>();
// Create directories if they don't exist
Directory.CreateDirectory(Path.GetDirectoryName(_issuesReportPath));
Directory.CreateDirectory(Path.GetDirectoryName(_noIssuesReportPath));
// Serialize reports to XML
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ComparisonReport));
using (var stream = new FileStream(_issuesReportPath, FileMode.Create))
{
serializer.Serialize(stream, issuesReport);
}
using (var stream = new FileStream(_noIssuesReportPath, FileMode.Create))
{
serializer.Serialize(stream, noIssuesReport);
}
// Update console output for both reports
Console.WriteLine($"Issues report saved to {_issuesReportPath}");
Console.WriteLine($"No-issues report saved to {_noIssuesReportPath}");
Console.WriteLine($"Errors: {assetsWithErrors.Count}");
Console.WriteLine($"Non-baselined issues: {issuesReport.AssetsWithIssues.Sum(m => m.Issues.Count)}");
Console.WriteLine($"Baselined issues: {noIssuesReport.AssetsWithIssues.Sum(m => m.Issues.Count)}");
// Print detailed issue counts by type
var allAssetWithIssues = assetsForReport.Where(mapping => mapping.Issues.Any()).ToList();
var issueCountsByType = allAssetWithIssues
.SelectMany(mapping => mapping.Issues)
.Where(issue => issue.Baseline == null)
.GroupBy(issue => issue.IssueType)
.ToDictionary(group => group.Key, group => group.Count());
var baselinedIssueCountsByType = allAssetWithIssues
.SelectMany(mapping => mapping.Issues)
.Where(issue => issue.Baseline != null)
.GroupBy(issue => issue.IssueType)
.ToDictionary(group => group.Key, group => group.Count());
Console.WriteLine("Detailed issue counts by type:");
foreach (var issueType in Enum.GetValues(typeof(IssueType)).Cast<IssueType>())
{
issueCountsByType.TryGetValue(issueType, out int issueCount);
baselinedIssueCountsByType.TryGetValue(issueType, out int baselinedIssueCount);
Console.WriteLine($" {issueType}: Issues w/o Baseline = {issueCount}, Baselined issues = {baselinedIssueCount}");
}
}
/// <summary>
/// Clones an asset mapping with filtered issues.
/// </summary>
/// <param name="original">Original asset mapping.</param>
/// <param name="issueFilter">Filter function for issues.</param>
/// <returns>Cloned asset mapping with filtered issues.</returns>
private static AssetMapping CloneAssetMappingWithFilteredIssues(AssetMapping original, Func<Issue, bool> issueFilter)
{
return new AssetMapping
{
Id = original.Id,
AssetType = original.AssetType,
DiffFilePath = original.DiffFilePath,
DiffManifestElement = original.DiffManifestElement,
BaseBuildFilePath = original.BaseBuildFilePath,
BaseBuildManifestElement = original.BaseBuildManifestElement,
EvaluationErrors = original.EvaluationErrors,
Issues = original.Issues.Where(issueFilter).ToList()
};
}
/// <summary>
/// Evaluates a single asset mapping for issues based on its type (Package or Blob).
/// </summary>
/// <param name="mapping">Asset mapping to evaluate</param>
private async Task EvaluateAsset(AssetMapping mapping)
{
if (mapping.AssetType == AssetType.Package)
{
await EvaluatePackage(mapping);
}
else if (mapping.AssetType == AssetType.Blob)
{
await EvaluateBlob(mapping);
}
}
/// <summary>
/// Evaluates a single package mapping for issues.
/// </summary>
/// <param name="mapping">The package asset mapping to evaluate.</param>
/// <returns>Task representing the asynchronous operation.</returns>
private async Task EvaluatePackage(AssetMapping mapping)
{
try
{
await _throttle.WaitAsync();
Console.WriteLine($"Evaluating '{mapping.Id}.");
// Filter away mappings that we do not care about
if (mapping.Id.Contains("Microsoft.SourceBuild.Intermediate"))
{
return;
}
// Check if the package is missing in the VMR
else if (!mapping.DiffElementFound)
{
mapping.Issues.Add(new Issue
{
IssueType = mapping.BaseBuildManifestElement.Attribute("NonShipping")?.Value == "true" ? IssueType.MissingNonShipping : IssueType.MissingShipping,
Description = $"Package '{mapping.Id}' is missing in the VMR."
});
return;
}
EvaluateClassification(mapping);
await EvaluatePackageContents(mapping);
}
catch (Exception e)
{
mapping.EvaluationErrors.Add(e.ToString());
}
finally
{
_throttle.Release();
}
}
static readonly ImmutableArray<string> IncludedAssemblyNameCheckFileExtensions = [".dll", ".exe"];
/// <summary>
/// Evaluate the contents of a mapping between two packages.
/// </summary>
/// <param name="mapping">Package mapping to evaluate</param>
public async Task EvaluatePackageContents(AssetMapping mapping)
{
var diffNugetPackagePath = mapping.DiffFilePath;
var baselineNugetPackagePath = mapping.BaseBuildFilePath;
// If either of the paths don't exist, we can't run this comparison
if (diffNugetPackagePath == null || baselineNugetPackagePath == null)
{
return;
}
try
{
using (PackageArchiveReader diffPackageReader = new PackageArchiveReader(File.OpenRead(diffNugetPackagePath)))
{
using (PackageArchiveReader baselinePackageReader = new PackageArchiveReader(baselineNugetPackagePath))
{
await ComparePackageFileLists(mapping, diffPackageReader, baselinePackageReader);
await ComparePackageAssemblyVersions(mapping, diffPackageReader, baselinePackageReader);
await ComparePackageMetadata(mapping, diffPackageReader, baselinePackageReader);
}
}
}
catch (Exception e)
{
mapping.EvaluationErrors.Add(e.ToString());
}
}
/// <summary>
/// Compare nuspecs for meaningful equality
/// </summary>
/// <param name="mapping">Mapping to compare</param>
/// <param name="diffPackageReader">Diff (VMR) package reader</param>
/// <param name="baselinePackageReader">Baseline package reader</param>
private async Task ComparePackageMetadata(AssetMapping mapping, PackageArchiveReader diffPackageReader, PackageArchiveReader baselinePackageReader)
{
try
{
var diffNuspecReader = await diffPackageReader.GetNuspecReaderAsync(CancellationToken.None);
var baseNuspecReader = await baselinePackageReader.GetNuspecReaderAsync(CancellationToken.None);
// Compare basic fields
ComparePackageMetadataStringField(mapping, "Authors", baseNuspecReader.GetAuthors(), diffNuspecReader.GetAuthors());
ComparePackageMetadataStringField(mapping, "ProjectUrl", baseNuspecReader.GetProjectUrl()?.ToString(), diffNuspecReader.GetProjectUrl()?.ToString());
ComparePackageMetadataStringField(mapping, "LicenseUrl", baseNuspecReader.GetLicenseUrl()?.ToString(), diffNuspecReader.GetLicenseUrl()?.ToString());
ComparePackageMetadataStringField(mapping, "Copyright", baseNuspecReader.GetCopyright(), diffNuspecReader.GetCopyright());
ComparePackageMetadataStringField(mapping, "Tags", baseNuspecReader.GetTags(), diffNuspecReader.GetTags());
// Compare target frameworks
var baseGroups = baseNuspecReader.GetDependencyGroups().ToList();
var diffGroups = diffNuspecReader.GetDependencyGroups().ToList();
var baseTfms = new HashSet<string>(baseGroups.Select(g => g.TargetFramework.GetShortFolderName()), StringComparer.OrdinalIgnoreCase);
var diffTfms = new HashSet<string>(diffGroups.Select(g => g.TargetFramework.GetShortFolderName()), StringComparer.OrdinalIgnoreCase);
if (!baseTfms.SetEquals(diffTfms))
{
mapping.Issues.Add(new Issue
{
IssueType = IssueType.PackageTFMs,
Description = $"Package target frameworks differ: base={string.Join(",", baseTfms)}, diff={string.Join(",", diffTfms)}"
});
}
// Compare dependencies within matching TFMs (ignore version differences)
foreach (var tfm in baseTfms.Intersect(diffTfms, StringComparer.OrdinalIgnoreCase))
{
var baseDeps = baseGroups.First(g => g.TargetFramework.GetShortFolderName().Equals(tfm, StringComparison.OrdinalIgnoreCase)).Packages;
var diffDeps = diffGroups.First(g => g.TargetFramework.GetShortFolderName().Equals(tfm, StringComparison.OrdinalIgnoreCase)).Packages;
var baseDepIds = new HashSet<string>(baseDeps.Select(d => d.Id), StringComparer.OrdinalIgnoreCase);
var diffDepIds = new HashSet<string>(diffDeps.Select(d => d.Id), StringComparer.OrdinalIgnoreCase);
if (!baseDepIds.SetEquals(diffDepIds))
{
var missingInDiff = baseDepIds.Except(diffDepIds);
var extraInDiff = diffDepIds.Except(baseDepIds);
mapping.Issues.Add(new Issue
{
IssueType = IssueType.PackageDependencies,
Description = $"Package dependencies differ in TFM '{tfm}'. "
+ $"Missing from diff: {string.Join(", ", missingInDiff)}; "
+ $"Extra in diff: {string.Join(", ", extraInDiff)}."
});
}
}
}
catch (Exception e)
{
mapping.EvaluationErrors.Add(e.ToString());
}
}
private void ComparePackageMetadataStringField(AssetMapping mapping, string fieldName, string baseValue, string diffValue)
{
if (!StringComparer.OrdinalIgnoreCase.Equals(baseValue ?? string.Empty, diffValue ?? string.Empty))
{
mapping.Issues.Add(new Issue
{
IssueType = IssueType.PackageMetadataDifference, // Reuse or define new IssueType if needed
Description = $"Package nuspec '{fieldName}': base='{baseValue}' vs diff='{diffValue}'"
});
}
}
/// <summary>
/// Compare the file lists of packages, identifying missing and extra files.
/// </summary>
/// <param name="mapping">Asset mapping to compare lists for</param>
/// <param name="diffPackageReader">Diff (VMR) package reader</param>
/// <param name="basePackageReader">Baseline (old build) package reader</param>
private async Task ComparePackageFileLists(AssetMapping mapping, PackageArchiveReader diffPackageReader, PackageArchiveReader basePackageReader)
{
IEnumerable<string> baselineFiles = (await basePackageReader.GetFilesAsync(CancellationToken.None));
IEnumerable<string> testFiles = (await diffPackageReader.GetFilesAsync(CancellationToken.None));
// Strip down the baseline and test files to remove version numbers.
var strippedBaselineFiles = baselineFiles.Select(f => RemoveVersionsNormalized(f)).ToList();
var strippedTestFiles = testFiles.Select(f => RemoveVersionsNormalized(f)).ToList();
var missingFiles = RemovePackageFilesToIgnore(strippedBaselineFiles.Except(strippedTestFiles));
foreach (var missingFile in missingFiles)
{
mapping.Issues.Add(new Issue
{
IssueType = IssueType.MissingPackageContent,
Description = missingFile,
});
}
// Compare the other way, and identify content in the VMR that is not in the baseline
var extraFiles = RemovePackageFilesToIgnore(strippedTestFiles.Except(strippedBaselineFiles));
foreach (var extraFile in extraFiles)
{
mapping.Issues.Add(new Issue
{
IssueType = IssueType.ExtraPackageContent,
Description = extraFile
});
}
static IEnumerable<string> RemovePackageFilesToIgnore(IEnumerable<string> files)
{
return files.Where(f => !f.EndsWith(".signature.p7s", StringComparison.OrdinalIgnoreCase) && !f.EndsWith(".psmdcp", StringComparison.OrdinalIgnoreCase));
}
}
/// <summary>
/// Compares the assembly versions of the files in the test and baseline packages.
/// </summary>
/// <param name="mapping">Mapping to evaluate</param>
/// <param name="diffPackageReader">Diff (VMR) package reader</param>
/// <param name="basePackageReader">Baseline (old build) package reader</param>
private static async Task ComparePackageAssemblyVersions(AssetMapping mapping, PackageArchiveReader diffPackageReader, PackageArchiveReader basePackageReader)
{
IEnumerable<string> baselineFiles = (await basePackageReader.GetFilesAsync(CancellationToken.None)).Where(f => IncludedAssemblyNameCheckFileExtensions.Contains(Path.GetExtension(f)));
IEnumerable<string> testFiles = (await diffPackageReader.GetFilesAsync(CancellationToken.None)).Where(f => IncludedAssemblyNameCheckFileExtensions.Contains(Path.GetExtension(f)));
foreach (var fileName in baselineFiles.Intersect(testFiles))
{
try
{
using var baselineStream = await CopyStreamToSeekableStreamAsync(basePackageReader.GetEntry(fileName).Open());
using var testStream = await CopyStreamToSeekableStreamAsync(diffPackageReader.GetEntry(fileName).Open());
CompareAssemblyVersions(mapping, fileName, baselineStream, testStream);
}
catch (Exception e)
{
mapping.EvaluationErrors.Add(e.ToString());
}
}
}
/// <summary>
/// Copies a stream from an archive to a seekable stream (MemoryStream).
/// </summary>
/// <param name="stream">Stream to copy</param>
/// <returns>Memory stream containing the stream contents.</returns>
private static async Task<Stream> CopyStreamToSeekableStreamAsync(Stream stream)
{
var outputStream = new MemoryStream();
await stream.CopyToAsync(outputStream, CancellationToken.None);
await stream.FlushAsync(CancellationToken.None);
outputStream.Position = 0;
return outputStream;
}
private static AssemblyName GetAssemblyName(Stream stream, string fileName)
{
using (var peReader = new PEReader(stream))
{
if (!peReader.HasMetadata)
{
return null;
}
var metadataReader = peReader.GetMetadataReader();
var assemblyDefinition = metadataReader.GetAssemblyDefinition();
var assemblyName = assemblyDefinition.GetAssemblyName();
return assemblyName;
}
}
/// <summary>
/// Evaluates the classification of an asset mapping. Is it correctly marked shipping or non-shipping?
/// </summary>
/// <param name="mapping">Mapping to evaluate</param>
private static void EvaluateClassification(AssetMapping mapping)
{
// Check for misclassification
bool isBaseShipping = mapping.BaseBuildManifestElement.Attribute("NonShipping")?.Value != "true";
bool isDiffShipping = mapping.DiffManifestElement.Attribute("NonShipping")?.Value != "true";
if (isBaseShipping != isDiffShipping)
{
mapping.Issues.Add(new Issue
{
IssueType = IssueType.MisclassifiedAsset,
Description = $"Asset '{mapping.Id}' is misclassified in the VMR. Base build is {(isBaseShipping ? "shipping" : "nonshipping")} and VMR build is {(isDiffShipping ? "shipping" : "nonshipping")}"
});
}
}
/// <summary>
/// Evaluates a single blob mapping for issues.
/// </summary>
/// <param name="mapping">Blob mapping to evaluate</param>
private async Task EvaluateBlob(AssetMapping mapping)
{
try
{
await _throttle.WaitAsync();
Console.WriteLine($"Evaluating '{mapping.Id}'");
// Filter away mappings that we do not care about
if (mapping.Id.Contains(".wixpack.zip"))
{
return;
}
if (mapping.Id.Contains("MergedManifest.xml"))
{
return;
}
// Check if the package is missing in the VMR
if (!mapping.DiffElementFound)
{
mapping.Issues.Add(new Issue
{
IssueType = mapping.BaseBuildManifestElement.Attribute("NonShipping")?.Value == "true" ? IssueType.MissingNonShipping : IssueType.MissingShipping,
Description = $"Blob '{mapping.Id}' is missing in the VMR."
});
return;
}
// Asset is found. Perform tests.
EvaluateClassification(mapping);
await EvaluateBlobContents(mapping);
}
catch (Exception e)
{
mapping.EvaluationErrors.Add(e.ToString());
}
finally
{
_throttle.Release();
}
}
public async Task EvaluateBlobContents(AssetMapping mapping)
{
// Switch on the file type, and call a helper based on the type
if (mapping.Id.EndsWith(".zip"))
{
await CompareZipArchiveContents(mapping);
}
else if (mapping.Id.EndsWith(".tar.gz") || mapping.Id.EndsWith(".tgz"))
{
await CompareTarArchiveContents(mapping);
}
}
private async Task CompareTarArchiveContents(AssetMapping mapping)
{
var diffTarPath = mapping.DiffFilePath;
var baselineTarPath = mapping.BaseBuildFilePath;
// If either of the paths don't exist, we can't run this comparison
if (diffTarPath == null || baselineTarPath == null)
{
return;
}
try
{
// Get the file lists for the baseline and diff tar files
IEnumerable<string> baselineFiles = GetTarGzArchiveFileList(baselineTarPath);
IEnumerable<string> diffFiles = GetTarGzArchiveFileList(diffTarPath);
// Compare file lists
CompareBlobArchiveFileLists(mapping, baselineFiles, diffFiles);
// Compare assembly versions
await CompareTarGzAssemblyVersions(mapping, baselineFiles, diffFiles);
}
catch (Exception e)
{
mapping.EvaluationErrors.Add(e.ToString());
}
}
/// <summary>
/// Retrieve the file list from a tar.gz file.
/// </summary>
/// <param name="archivePath"></param>
/// <returns></returns>
private List<string> GetTarGzArchiveFileList(string archivePath)
{
List<string> entries = new();
using (FileStream fileStream = File.OpenRead(archivePath))
{
using (GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Decompress))
using (TarReader reader = new TarReader(gzipStream))
{
TarEntry entry;
while ((entry = reader.GetNextEntry()) != null)
{
entries.Add(entry.Name);
}
}
}
return entries;
}
/// <summary>
/// Compare the assembly versions in a tar.gz file.
/// </summary>
/// <param name="mapping">Mapping to compare</param>
/// <param name="baselineFiles">Files existing in the baseline archive</param>
/// <param name="diffFiles">Files existing in the diff archive</param>
private async Task CompareTarGzAssemblyVersions(AssetMapping mapping, IEnumerable<string> baselineFiles, IEnumerable<string> diffFiles)
{
// Get the list of common files and create a map of file->stream
var strippedBaselineFiles = baselineFiles.Select(f => RemoveVersionsNormalized(f)).ToList();
var strippedDiffFiles = diffFiles.Select(f => RemoveVersionsNormalized(f)).ToList();
var commonFiles = strippedBaselineFiles.Intersect(strippedDiffFiles).ToHashSet();
var baselineStreams = new Dictionary<string, Stream>();
var diffStreams = new Dictionary<string, Stream>();
using (FileStream baseStream = File.OpenRead(mapping.BaseBuildFilePath))
{
using (FileStream diffStream = File.OpenRead(mapping.DiffFilePath))
{
using (GZipStream baseGzipStream = new GZipStream(baseStream, CompressionMode.Decompress))
using (TarReader baseReader = new TarReader(baseGzipStream))
{
using (GZipStream diffGzipStream = new GZipStream(diffStream, CompressionMode.Decompress))
using (TarReader diffReader = new TarReader(diffGzipStream))
{
string nextBaseEntry = null;
string nextDiffEntry = null;
do
{
nextBaseEntry = await WalkNextCommon(commonFiles, baseReader, baselineStreams);
if (nextBaseEntry != null)
{
CompareAvailableStreams(mapping, baselineStreams, diffStreams, nextBaseEntry);
}
nextDiffEntry = await WalkNextCommon(commonFiles, diffReader, diffStreams);
if (nextDiffEntry != null)
{
CompareAvailableStreams(mapping, baselineStreams, diffStreams, nextDiffEntry);
}
}
while (nextBaseEntry != null || nextDiffEntry != null);
// If there are any remaining streams, create an evaluation error
if (baselineStreams.Count > 0 || diffStreams.Count > 0)
{
mapping.EvaluationErrors.Add("Failed to compare all tar entries.");
}
}
}
}
}
// Walk the tar to the next entry that exists in both the base and the diff
static async Task<string> WalkNextCommon(HashSet<string> commonFiles, TarReader reader, Dictionary<string, Stream> streams)
{
TarEntry baseEntry;
while ((baseEntry = reader.GetNextEntry()) != null && baseEntry.DataStream != null)
{
string entryStripped = RemoveVersionsNormalized(baseEntry.Name);
// If the element lives in the common files hash set, then copy it to a memory stream.
// Do not close the stream.
if (commonFiles.Contains(entryStripped))
{
streams[entryStripped] = await CopyStreamToSeekableStreamAsync(baseEntry.DataStream);
return entryStripped;
}
}
return null;
}
// Given we have a new entry that is common between base and diff, attempt to do some comparisons.
void CompareAvailableStreams(AssetMapping mapping, Dictionary<string, Stream> baselineStreams, Dictionary<string, Stream> diffStreams,
string entry)
{
if (baselineStreams.TryGetValue(entry, out var baselineFileStream) &&
diffStreams.TryGetValue(entry, out var diffFileStream))
{
CompareAssemblyVersions(mapping, entry, baselineFileStream, diffFileStream);
baselineFileStream.Dispose();
diffFileStream.Dispose();
baselineStreams.Remove(entry);
diffStreams.Remove(entry);
}
}
}
private static string RemoveVersionsNormalized(string path)
{
string strippedPath = path.Replace("\\", "//");
string prevPath = path;
do
{
prevPath = strippedPath;
strippedPath = VersionIdentifier.RemoveVersions(strippedPath);
} while (prevPath != strippedPath);
return strippedPath;
}
private async Task CompareZipArchiveContents(AssetMapping mapping)
{
var diffZipPath = mapping.DiffFilePath;
var baselineZipPath = mapping.BaseBuildFilePath;
// If either of the paths don't exist, we can't run this comparison
if (diffZipPath == null || baselineZipPath == null)
{
return;
}
try
{
using (var diffStream = File.OpenRead(diffZipPath))
using (var baselineStream = File.OpenRead(baselineZipPath))
{
using (var diffArchive = new ZipArchive(diffStream, ZipArchiveMode.Read))
using (var baselineArchive = new ZipArchive(baselineStream, ZipArchiveMode.Read))
{
CompareZipFileLists(mapping, diffArchive, baselineArchive);
await CompareZipAssemblyVersions(mapping, diffArchive, baselineArchive);
}
}
}
catch (Exception e)
{
mapping.EvaluationErrors.Add(e.ToString());
}
}
private void CompareZipFileLists(AssetMapping mapping, ZipArchive diffArchive, ZipArchive baselineArchive)
{
IEnumerable<string> baselineFiles = baselineArchive.Entries.Select(e => e.FullName);
IEnumerable<string> diffFiles = diffArchive.Entries.Select(e => e.FullName);
CompareBlobArchiveFileLists(mapping, baselineFiles, diffFiles);
}
private async Task CompareZipAssemblyVersions(AssetMapping mapping, ZipArchive diffArchive, ZipArchive baselineArchive)
{
IEnumerable<string> baselineFiles = baselineArchive.Entries.Select(e => e.FullName).Where(f => IncludedAssemblyNameCheckFileExtensions.Contains(Path.GetExtension(f)));
IEnumerable<string> diffFiles = diffArchive.Entries.Select(e => e.FullName).Where(f => IncludedAssemblyNameCheckFileExtensions.Contains(Path.GetExtension(f)));
foreach (var fileName in baselineFiles.Intersect(diffFiles))
{
try
{
using var baselineStream = await CopyStreamToSeekableStreamAsync(baselineArchive.GetEntry(fileName).Open());
using var testStream = await CopyStreamToSeekableStreamAsync(diffArchive.GetEntry(fileName).Open());
CompareAssemblyVersions(mapping, fileName, baselineStream, testStream);
}
catch (Exception e)
{
mapping.EvaluationErrors.Add(e.ToString());
}
}
}
private static void CompareAssemblyVersions(AssetMapping mapping, string fileName, Stream baselineStream, Stream testStream)
{
AssemblyName baselineAssemblyName = null;
try
{
baselineAssemblyName = GetAssemblyName(baselineStream, fileName);
}
catch (BadImageFormatException)
{
// Assume the file is not an assembly, and then don't attempt for the test assembly
return;
}
AssemblyName testAssemblyName = GetAssemblyName(testStream, fileName);
if ((baselineAssemblyName == null) != (testAssemblyName == null))
{
mapping.Issues.Add(new Issue
{
IssueType = IssueType.AssemblyVersionMismatch,
Description = $"Assembly '{fileName}' in {mapping.AssetType.ToString().ToLowerInvariant()} '{mapping.Id}' has different but unknown versions in the VMR and base build."
});
}
else if (baselineAssemblyName == null && testAssemblyName == null)
{
return;
}
if (baselineAssemblyName.ToString() != testAssemblyName.ToString())
{
mapping.Issues.Add(new Issue
{
IssueType = IssueType.AssemblyVersionMismatch,
Description = $"Assembly '{fileName}' in {mapping.AssetType.ToString().ToLowerInvariant()} '{mapping.Id}'. " +
$"VMR version: {baselineAssemblyName}, base build version: {testAssemblyName}"
});
}
}
private static void CompareBlobArchiveFileLists(AssetMapping mapping, IEnumerable<string> baselineFiles, IEnumerable<string> diffFiles)
{
// Because these typically contain version numbers in their paths, we need to go and remove those.
var strippedBaselineFiles = baselineFiles.Select(f => RemoveVersionsNormalized(f)).ToList();
var strippedDiffFiles = diffFiles.Select(f => RemoveVersionsNormalized(f)).ToList();
var missingFiles = strippedBaselineFiles.Except(strippedDiffFiles);
foreach (var missingFile in missingFiles)
{
mapping.Issues.Add(new Issue
{
IssueType = IssueType.MissingPackageContent,
Description = missingFile
});
}
// Compare the other way, and identify content in the VMR that is not in the baseline
var extraFiles = strippedDiffFiles.Except(strippedBaselineFiles);
foreach (var extraFile in extraFiles)
{
mapping.Issues.Add(new Issue