forked from dotnet/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResolvePackageAssets.cs
1818 lines (1579 loc) · 74.7 KB
/
ResolvePackageAssets.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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using NuGet.Common;
using NuGet.ProjectModel;
using NuGet.Versioning;
namespace Microsoft.NET.Build.Tasks
{
/// <summary>
/// Resolve package assets from projects.assets.json into MSBuild items.
///
/// Optimized for fast incrementality using an intermediate, binary assets.cache
/// file that contains only the data that is actually returned for the current
/// TFM/RID/etc. and written in a format that is easily decoded to ITaskItem
/// arrays without undue allocation.
/// </summary>
public sealed class ResolvePackageAssets : TaskBase
{
/// <summary>
/// Path to assets.json.
/// </summary>
public string ProjectAssetsFile { get; set; }
/// <summary>
/// Path to assets.cache file.
/// </summary>
[Required]
public string ProjectAssetsCacheFile { get; set; }
/// <summary>
/// Path to project file (.csproj|.vbproj|.fsproj)
/// </summary>
[Required]
public string ProjectPath { get; set; }
/// <summary>
/// TargetFramework to use for compile-time assets.
/// </summary>
[Required]
public string TargetFramework { get; set; }
/// <summary>
/// RID to use for runtime assets (may be empty)
/// </summary>
public string RuntimeIdentifier { get; set; }
/// <summary>
/// The platform library name for resolving copy local assets.
/// </summary>
public string PlatformLibraryName { get; set; }
/// <summary>
/// The runtime frameworks for resolving copy local assets.
/// </summary>
public ITaskItem[] RuntimeFrameworks { get; set; }
/// <summary>
/// Whether or not the the copy local is for a self-contained application.
/// </summary>
public bool IsSelfContained { get; set; }
/// <summary>
/// The languages to filter the resource assmblies for.
/// </summary>
public ITaskItem[] SatelliteResourceLanguages { get; set; }
/// <summary>
/// Do not write package assets cache to disk nor attempt to read previous cache from disk.
/// </summary>
public bool DisablePackageAssetsCache { get; set; }
/// <summary>
/// Do not generate transitive project references.
/// </summary>
public bool DisableTransitiveProjectReferences { get; set; }
/// <summary>
/// Disables FrameworkReferences from referenced projects or packages
/// </summary>
public bool DisableTransitiveFrameworkReferences { get; set; }
/// <summary>
/// Do not add references to framework assemblies as specified by packages.
/// </summary>
public bool DisableFrameworkAssemblies { get; set; }
/// <summary>
/// Whether or not resolved runtime target assets should be copied locally.
/// </summary>
public bool CopyLocalRuntimeTargetAssets { get; set; }
/// <summary>
/// Log messages from assets log to build error/warning/message.
/// </summary>
public bool EmitAssetsLogMessages { get; set; }
/// <summary>
/// Set ExternallyResolved=true metadata on reference items to indicate to MSBuild ResolveAssemblyReferences
/// that these are resolved by an external system (in this case nuget) and therefore several steps can be
/// skipped as an optimization.
/// </summary>
public bool MarkPackageReferencesAsExternallyResolved { get; set; }
/// <summary>
/// Project language ($(ProjectLanguage) in common targets -"VB" or "C#" or "F#" ).
/// Impacts applicability of analyzer assets.
/// </summary>
public string ProjectLanguage { get; set; }
/// <summary>
/// Optional version of the compiler API (E.g. 'roslyn3.9', 'roslyn4.0')
/// Impacts applicability of analyzer assets.
/// </summary>
public string CompilerApiVersion { get; set; }
/// <summary>
/// Check that there is at least one package dependency in the RID graph that is not in the RID-agnostic graph.
/// Used as a heuristic to detect invalid RIDs.
/// </summary>
public bool EnsureRuntimePackageDependencies { get; set; }
/// <summary>
/// Specifies whether to validate that the version of the implicit platform packages in the assets
/// file matches the version specified by <see cref="ExpectedPlatformPackages"/>
/// </summary>
public bool VerifyMatchingImplicitPackageVersion { get; set; }
/// <summary>
/// Implicitly referenced platform packages. If set, then an error will be generated if the
/// version of the specified packages from the assets file does not match the expected versions.
/// </summary>
public ITaskItem[] ExpectedPlatformPackages { get; set; }
/// <summary>
/// The RuntimeIdentifiers that shims will be generated for.
/// </summary>
public ITaskItem[] ShimRuntimeIdentifiers { get; set; }
public ITaskItem[] PackageReferences { get; set; }
/// <summary>
/// The file name of Apphost asset.
/// </summary>
[Required]
public string DotNetAppHostExecutableNameWithoutExtension { get; set; }
/// <summary>
/// True indicates we are doing a design-time build. Otherwise we are in a build.
/// </summary>
public bool DesignTimeBuild { get; set; }
/// <summary>
/// Full paths to assemblies from packages to pass to compiler as analyzers.
/// </summary>
[Output]
public ITaskItem[] Analyzers { get; private set; }
/// <summary>
/// Full paths to assemblies from packages to compiler as references.
/// </summary>
[Output]
public ITaskItem[] CompileTimeAssemblies { get; private set; }
/// <summary>
/// Content files from package that require preprocessing.
/// Content files that do not require preprocessing are written directly to .g.props by nuget restore.
/// </summary>
[Output]
public ITaskItem[] ContentFilesToPreprocess { get; private set; }
/// <summary>
/// Simple names of framework assemblies that packages request to be added as framework references.
/// </summary>
[Output]
public ITaskItem[] FrameworkAssemblies { get; private set; }
[Output]
public ITaskItem[] FrameworkReferences { get; private set; }
/// <summary>
/// Full paths to native libraries from packages to run against.
/// </summary>
[Output]
public ITaskItem[] NativeLibraries { get; private set; }
/// <summary>
/// The package folders from the assets file (ie the paths under which package assets may be found)
/// </summary>
[Output]
public ITaskItem[] PackageFolders { get; set; }
/// <summary>
/// Full paths to satellite assemblies from packages.
/// </summary>
[Output]
public ITaskItem[] ResourceAssemblies { get; private set; }
/// <summary>
/// Full paths to managed assemblies from packages to run against.
/// </summary>
[Output]
public ITaskItem[] RuntimeAssemblies { get; private set; }
/// <summary>
/// Full paths to RID-specific assets that go in runtimes/ folder on publish.
/// </summary>
[Output]
public ITaskItem[] RuntimeTargets { get; private set; }
/// <summary>
/// Relative paths to project files that are referenced transitively (but not directly).
/// </summary>
[Output]
public ITaskItem[] TransitiveProjectReferences { get; private set; }
/// <summary>
/// Relative paths for Apphost for different ShimRuntimeIdentifiers with RuntimeIdentifier as meta data
/// </summary>
[Output]
public ITaskItem[] ApphostsForShimRuntimeIdentifiers { get; private set; }
[Output]
public ITaskItem[] PackageDependencies { get; private set; }
/// <summary>
/// List of symbol files (.pdb) related to NuGet packages.
/// </summary>
/// <remarks>
/// Pdb files to be copied to the output directory
/// </remarks>
[Output]
public ITaskItem[] DebugSymbolsFiles { get; private set;}
/// <summary>
/// List of xml files related to NuGet packages.
/// </summary>
/// <remarks>
/// The XML files should only be included in the publish output if PublishReferencesDocumentationFiles is true
/// </remarks>
[Output]
public ITaskItem[] ReferenceDocumentationFiles { get; private set; }
/// <summary>
/// Messages from the assets file.
/// These are logged directly and therefore not returned to the targets (note private here).
/// However,they are still stored as ITaskItem[] so that the same cache reader/writer code
/// can be used for message items and asset items.
/// </summary>
private ITaskItem[] _logMessages;
////////////////////////////////////////////////////////////////////////////////////////////////////
// Package Asset Cache File Format Details
//
// Encodings of Int32, Byte[], String as defined by System.IO.BinaryReader/Writer.
//
// There are 3 sections, written in the following order:
//
// 1. Header
// ---------
// Encodes format and enough information to quickly decide if cache is still valid.
//
// Header:
// Int32 Signature: Spells PKGA ("package assets") when 4 little-endian bytes are interpreted as ASCII chars.
// Int32 Version: Increased whenever format changes to prevent issues when building incrementally with a different SDK.
// Byte[] SettingsHash: SHA-256 of settings that require the cache to be invalidated when changed.
// Int32 MetadataStringTableOffset: Byte offset in file to start of the metadata string table.
//
// 2. ItemGroup[] ItemGroups
// --------------
// There is one ItemGroup for each ITaskItem[] output (Analyzers, CompileTimeAssemblies, etc.)
// Count and order of item groups is constant and therefore not encoded in to the file.
//
// ItemGroup:
// Int32 ItemCount
// Item[] Items
//
// Item:
// String ItemSpec (not index to string table because it generally unique)
// Int32 MetadataCount
// Metadata[] Metadata
//
// Metadata:
// Int32 Key: Index in to MetadataStringTable for metadata key
// Int32 Value: Index in to MetadataStringTable for metadata value
//
// 3. MetadataStringTable
// ----------------------
// Indexes keys and values of item metadata to compress the cache file
//
// MetadataStringTable:
// Int32 MetadataStringCount
// String[] MetadataStrings
////////////////////////////////////////////////////////////////////////////////////////////////////
private const int CacheFormatSignature = ('P' << 0) | ('K' << 8) | ('G' << 16) | ('A' << 24);
private const int CacheFormatVersion = 11;
private static readonly Encoding TextEncoding = Encoding.UTF8;
private const int SettingsHashLength = 256 / 8;
private HashAlgorithm CreateSettingsHash() => SHA256.Create();
protected override void ExecuteCore()
{
if (string.IsNullOrEmpty(ProjectAssetsFile))
{
throw new BuildErrorException(Strings.AssetsFileNotSet);
}
ReadItemGroups();
SetImplicitMetadataForCompileTimeAssemblies();
SetImplicitMetadataForFrameworkAssemblies();
LogMessagesToMSBuild();
}
private void ReadItemGroups()
{
using (var reader = new CacheReader(this))
{
// NOTE: Order (alphabetical by group name followed by log messages) must match writer.
Analyzers = reader.ReadItemGroup();
ApphostsForShimRuntimeIdentifiers = reader.ReadItemGroup();
CompileTimeAssemblies = reader.ReadItemGroup();
ContentFilesToPreprocess = reader.ReadItemGroup();
DebugSymbolsFiles = reader.ReadItemGroup();
FrameworkAssemblies = reader.ReadItemGroup();
FrameworkReferences = reader.ReadItemGroup();
NativeLibraries = reader.ReadItemGroup();
PackageDependencies = reader.ReadItemGroup();
PackageFolders = reader.ReadItemGroup();
ReferenceDocumentationFiles = reader.ReadItemGroup();
ResourceAssemblies = reader.ReadItemGroup();
RuntimeAssemblies = reader.ReadItemGroup();
RuntimeTargets = reader.ReadItemGroup();
TransitiveProjectReferences = reader.ReadItemGroup();
_logMessages = reader.ReadItemGroup();
}
}
private void SetImplicitMetadataForCompileTimeAssemblies()
{
string externallyResolved = MarkPackageReferencesAsExternallyResolved ? "true" : "";
foreach (var item in CompileTimeAssemblies)
{
item.SetMetadata(MetadataKeys.NuGetSourceType, "Package");
item.SetMetadata(MetadataKeys.Private, "false");
item.SetMetadata(MetadataKeys.HintPath, item.ItemSpec);
item.SetMetadata(MetadataKeys.ExternallyResolved, externallyResolved);
}
}
private void SetImplicitMetadataForFrameworkAssemblies()
{
foreach (var item in FrameworkAssemblies)
{
item.SetMetadata(MetadataKeys.NuGetIsFrameworkReference, "true");
item.SetMetadata(MetadataKeys.NuGetSourceType, "Package");
item.SetMetadata(MetadataKeys.Pack, "false");
item.SetMetadata(MetadataKeys.Private, "false");
}
}
private void LogMessagesToMSBuild()
{
if (!EmitAssetsLogMessages)
{
return;
}
foreach (var item in _logMessages)
{
Log.Log(
new Message(
text: item.ItemSpec,
level: GetMessageLevel(item.GetMetadata(MetadataKeys.Severity)),
code: item.GetMetadata(MetadataKeys.DiagnosticCode),
file: ProjectPath));
}
}
private static MessageLevel GetMessageLevel(string severity)
{
switch (severity)
{
case nameof(LogLevel.Error):
return MessageLevel.Error;
case nameof(LogLevel.Warning):
return MessageLevel.Warning;
default:
return MessageLevel.NormalImportance;
}
}
internal byte[] HashSettings()
{
using (var stream = new MemoryStream())
{
using (var writer = new BinaryWriter(stream, TextEncoding, leaveOpen: true))
{
writer.Write(DisablePackageAssetsCache);
writer.Write(DisableFrameworkAssemblies);
writer.Write(CopyLocalRuntimeTargetAssets);
writer.Write(DisableTransitiveProjectReferences);
writer.Write(DisableTransitiveFrameworkReferences);
writer.Write(DotNetAppHostExecutableNameWithoutExtension);
writer.Write(EmitAssetsLogMessages);
writer.Write(EnsureRuntimePackageDependencies);
writer.Write(MarkPackageReferencesAsExternallyResolved);
if (PackageReferences != null)
{
foreach (var packageReference in PackageReferences)
{
writer.Write(packageReference.ItemSpec ?? "");
writer.Write(packageReference.GetMetadata(MetadataKeys.Version));
writer.Write(packageReference.GetMetadata(MetadataKeys.Publish));
}
}
if (ExpectedPlatformPackages != null)
{
foreach (var implicitPackage in ExpectedPlatformPackages)
{
writer.Write(implicitPackage.ItemSpec ?? "");
writer.Write(implicitPackage.GetMetadata(MetadataKeys.Version) ?? "");
}
}
writer.Write(ProjectAssetsCacheFile);
writer.Write(ProjectAssetsFile ?? "");
writer.Write(PlatformLibraryName ?? "");
if (RuntimeFrameworks != null)
{
foreach (var framework in RuntimeFrameworks)
{
writer.Write(framework.ItemSpec ?? "");
}
}
writer.Write(IsSelfContained);
if (SatelliteResourceLanguages != null)
{
foreach (var language in SatelliteResourceLanguages)
{
writer.Write(language.ItemSpec ?? "");
}
}
writer.Write(ProjectLanguage ?? "");
writer.Write(CompilerApiVersion ?? "");
writer.Write(ProjectPath);
writer.Write(RuntimeIdentifier ?? "");
if (ShimRuntimeIdentifiers != null)
{
foreach (var r in ShimRuntimeIdentifiers)
{
writer.Write(r.ItemSpec ?? "");
}
}
writer.Write(TargetFramework);
writer.Write(VerifyMatchingImplicitPackageVersion);
}
stream.Position = 0;
using (var hash = CreateSettingsHash())
{
return hash.ComputeHash(stream);
}
}
}
private sealed class CacheReader : IDisposable
{
private BinaryReader _reader;
private string[] _metadataStringTable;
public CacheReader(ResolvePackageAssets task)
{
byte[] settingsHash = task.HashSettings();
if (!task.DisablePackageAssetsCache)
{
// I/O errors can occur here if there are parallel calls to resolve package assets
// for the same project configured with the same intermediate directory. This can
// (for example) happen when design-time builds and real builds overlap.
//
// If there is an I/O error, then we fall back to the same in-memory approach below
// as when DisablePackageAssetsCache is set to true.
try
{
_reader = CreateReaderFromDisk(task, settingsHash);
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
}
if (_reader == null)
{
_reader = CreateReaderFromMemory(task, settingsHash);
}
ReadMetadataStringTable();
}
private static BinaryReader CreateReaderFromMemory(ResolvePackageAssets task, byte[] settingsHash)
{
if (!task.DisablePackageAssetsCache)
{
task.Log.LogMessage(MessageImportance.High, Strings.UnableToUsePackageAssetsCache_Info);
}
Stream stream;
using (var writer = new CacheWriter(task))
{
stream = writer.WriteToMemoryStream();
}
return OpenCacheStream(stream, settingsHash);
}
private static BinaryReader CreateReaderFromDisk(ResolvePackageAssets task, byte[] settingsHash)
{
Debug.Assert(!task.DisablePackageAssetsCache);
BinaryReader reader = null;
try
{
if (IsCacheFileUpToDate())
{
reader = OpenCacheFile(task.ProjectAssetsCacheFile, settingsHash);
}
}
catch (IOException) { }
catch (InvalidDataException) { }
catch (UnauthorizedAccessException) { }
if (reader == null)
{
using (var writer = new CacheWriter(task))
{
if (writer.CanWriteToCacheFile)
{
writer.WriteToCacheFile();
reader = OpenCacheFile(task.ProjectAssetsCacheFile, settingsHash);
}
else
{
var stream = writer.WriteToMemoryStream();
reader = OpenCacheStream(stream, settingsHash);
}
}
}
return reader;
bool IsCacheFileUpToDate() => File.GetLastWriteTimeUtc(task.ProjectAssetsCacheFile) > File.GetLastWriteTimeUtc(task.ProjectAssetsFile);
}
private static BinaryReader OpenCacheStream(Stream stream, byte[] settingsHash)
{
var reader = new BinaryReader(stream, TextEncoding, leaveOpen: false);
try
{
ValidateHeader(reader, settingsHash);
}
catch
{
reader.Dispose();
throw;
}
return reader;
}
private static BinaryReader OpenCacheFile(string path, byte[] settingsHash)
{
var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
return OpenCacheStream(stream, settingsHash);
}
private static void ValidateHeader(BinaryReader reader, byte[] settingsHash)
{
if (reader.ReadInt32() != CacheFormatSignature
|| reader.ReadInt32() != CacheFormatVersion
|| !reader.ReadBytes(SettingsHashLength).SequenceEqual(settingsHash))
{
throw new InvalidDataException();
}
}
private void ReadMetadataStringTable()
{
int stringTablePosition = _reader.ReadInt32();
int savedPosition = Position;
Position = stringTablePosition;
_metadataStringTable = new string[_reader.ReadInt32()];
for (int i = 0; i < _metadataStringTable.Length; i++)
{
_metadataStringTable[i] = _reader.ReadString();
}
Position = savedPosition;
}
private int Position
{
get => checked((int)_reader.BaseStream.Position);
set => _reader.BaseStream.Position = value;
}
public void Dispose()
{
_reader.Dispose();
}
internal ITaskItem[] ReadItemGroup()
{
var items = new ITaskItem[_reader.ReadInt32()];
for (int i = 0; i < items.Length; i++)
{
items[i] = ReadItem();
}
return items;
}
private ITaskItem ReadItem()
{
var item = new TaskItem(_reader.ReadString());
int metadataCount = _reader.ReadInt32();
for (int i = 0; i < metadataCount; i++)
{
string key = _metadataStringTable[_reader.ReadInt32()];
string value = _metadataStringTable[_reader.ReadInt32()];
item.SetMetadata(key, value);
}
return item;
}
}
internal sealed class CacheWriter : IDisposable
{
private const int InitialStringTableCapacity = 32;
private ResolvePackageAssets _task;
private BinaryWriter _writer;
private LockFile _lockFile;
private LockFileTarget _compileTimeTarget;
private IPackageResolver _packageResolver;
private LockFileTarget _runtimeTarget;
private Dictionary<string, int> _stringTable;
private List<string> _metadataStrings;
private List<int> _bufferedMetadata;
private HashSet<string> _copyLocalPackageExclusions;
private HashSet<string> _publishPackageExclusions;
private Placeholder _metadataStringTablePosition;
private string _targetFramework;
private int _itemCount;
public bool CanWriteToCacheFile { get; set; }
private bool MismatchedAssetsFile => !CanWriteToCacheFile;
private const string NetCorePlatformLibrary = "Microsoft.NETCore.App";
private const char RelatedPropertySeparator = ';';
/// <summary>
/// This constructor should only be used for testing - IPackgeResolver carries a lot of
/// state so using mocks really help with testing this component.
/// </summary>
public CacheWriter(ResolvePackageAssets task, IPackageResolver resolver) : this(task)
{
_packageResolver = resolver;
}
public CacheWriter(ResolvePackageAssets task)
{
_targetFramework = task.TargetFramework;
_task = task;
_lockFile = new LockFileCache(task).GetLockFile(task.ProjectAssetsFile);
_packageResolver = NuGetPackageResolver.CreateResolver(_lockFile);
// If we are doing a design-time build, we do not want to fail the build if we can't find the
// target framework and/or runtime identifier in the assets file. This is because the design-time
// build needs to succeed in order to get the right information in order to run a restore in order
// to write the assets file with the correct information.
// So if we can't find the right target in the lock file and are doing a design-time build, we use
// an empty lock file target instead of throwing an error, and we don't save the results to the
// cache file.
CanWriteToCacheFile = true;
if (task.DesignTimeBuild)
{
_compileTimeTarget = _lockFile.GetTargetAndReturnNullIfNotFound(_targetFramework, runtimeIdentifier: null);
_runtimeTarget = _lockFile.GetTargetAndReturnNullIfNotFound(_targetFramework, _task.RuntimeIdentifier);
if (_compileTimeTarget == null)
{
_compileTimeTarget = new LockFileTarget();
CanWriteToCacheFile = false;
}
if (_runtimeTarget == null)
{
_runtimeTarget = new LockFileTarget();
CanWriteToCacheFile = false;
}
}
else
{
_compileTimeTarget = _lockFile.GetTargetAndThrowIfNotFound(_targetFramework, runtimeIdentifier: null);
_runtimeTarget = _lockFile.GetTargetAndThrowIfNotFound(_targetFramework, _task.RuntimeIdentifier);
}
_stringTable = new Dictionary<string, int>(InitialStringTableCapacity, StringComparer.Ordinal);
_metadataStrings = new List<string>(InitialStringTableCapacity);
_bufferedMetadata = new List<int>();
// If the assets file doesn't match the inputs, don't bother trying to compute package exclusions
if (!MismatchedAssetsFile)
{
ComputePackageExclusions();
}
}
public void WriteToCacheFile()
{
Directory.CreateDirectory(Path.GetDirectoryName(_task.ProjectAssetsCacheFile));
var stream = File.Open(_task.ProjectAssetsCacheFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
using (_writer = new BinaryWriter(stream, TextEncoding, leaveOpen: false))
{
Write();
}
}
public Stream WriteToMemoryStream()
{
var stream = new MemoryStream();
_writer = new BinaryWriter(stream, TextEncoding, leaveOpen: true);
Write();
stream.Position = 0;
return stream;
}
public void Dispose()
{
_writer?.Dispose();
_writer = null;
}
private void FlushMetadata()
{
if (_itemCount == 0)
{
return;
}
Debug.Assert((_bufferedMetadata.Count % 2) == 0);
_writer.Write(_bufferedMetadata.Count / 2);
foreach (int m in _bufferedMetadata)
{
_writer.Write(m);
}
_bufferedMetadata.Clear();
}
private void Write()
{
WriteHeader();
WriteItemGroups();
WriteMetadataStringTable();
// Write signature last so that we will not attempt to use an incomplete cache file and instead
// regenerate it.
WriteToPlaceholder(new Placeholder(0), CacheFormatSignature);
}
private void WriteHeader()
{
// Leave room for signature, which we only write at the very end so that we will
// not attempt to use a cache file corrupted by a prior crash.
WritePlaceholder();
_writer.Write(CacheFormatVersion);
_writer.Write(_task.HashSettings());
_metadataStringTablePosition = WritePlaceholder();
}
private void WriteItemGroups()
{
// NOTE: Order (alphabetical by group name followed by log messages) must match reader.
WriteItemGroup(WriteAnalyzers);
WriteItemGroup(WriteApphostsForShimRuntimeIdentifiers);
WriteItemGroup(WriteCompileTimeAssemblies);
WriteItemGroup(WriteContentFilesToPreprocess);
WriteItemGroup(WriteDebugSymbolsFiles);
WriteItemGroup(WriteFrameworkAssemblies);
WriteItemGroup(WriteFrameworkReferences);
WriteItemGroup(WriteNativeLibraries);
WriteItemGroup(WritePackageDependencies);
WriteItemGroup(WritePackageFolders);
WriteItemGroup(WriteReferenceDocumentationFiles);
WriteItemGroup(WriteResourceAssemblies);
WriteItemGroup(WriteRuntimeAssemblies);
WriteItemGroup(WriteRuntimeTargets);
WriteItemGroup(WriteTransitiveProjectReferences);
WriteItemGroup(WriteLogMessages);
}
private void WriteMetadataStringTable()
{
int savedPosition = Position;
_writer.Write(_metadataStrings.Count);
foreach (var s in _metadataStrings)
{
_writer.Write(s);
}
WriteToPlaceholder(_metadataStringTablePosition, savedPosition);
}
private int Position
{
get => checked((int)_writer.BaseStream.Position);
set => _writer.BaseStream.Position = value;
}
private struct Placeholder
{
public readonly int Position;
public Placeholder(int position) { Position = position; }
}
private Placeholder WritePlaceholder()
{
var placeholder = new Placeholder(Position);
_writer.Write(int.MinValue);
return placeholder;
}
private void WriteToPlaceholder(Placeholder placeholder, int value)
{
int savedPosition = Position;
Position = placeholder.Position;
_writer.Write(value);
Position = savedPosition;
}
class LibraryComparer : IEqualityComparer<(string, NuGetVersion)>
{
public bool Equals((string, NuGetVersion) l1, (string, NuGetVersion) l2)
{
return StringComparer.OrdinalIgnoreCase.Equals(l1.Item1, l2.Item1)
&& l1.Item2.Equals(l2.Item2);
}
public int GetHashCode((string, NuGetVersion) library)
{
#if NET
return HashCode.Combine(
StringComparer.OrdinalIgnoreCase.GetHashCode(library.Item1),
library.Item2.GetHashCode());
#else
int hashCode = -1507694697;
hashCode = hashCode * -1521134295 + StringComparer.OrdinalIgnoreCase.GetHashCode(library.Item1);
hashCode = hashCode * -1521134295 + library.Item2.GetHashCode();
return hashCode;
#endif
}
}
private void WriteAnalyzers()
{
AnalyzerResolver resolver = new AnalyzerResolver(this);
foreach (var library in _lockFile.Libraries)
{
if (!library.IsPackage())
{
continue;
}
foreach (var file in library.Files)
{
resolver.AddFile(file, library);
}
resolver.CompleteLibraryAnalyzers();
}
}
/// <summary>
/// Resolves the correct analyzer assets from a NuGet package.
/// </summary>
/// <remarks>
/// This allows packages to ship multiple analyzers that target different versions
/// of the compiler. For example, a package may include:
///
/// "analyzers/dotnet/roslyn3.7/analyzer.dll"
/// "analyzers/dotnet/roslyn3.8/analyzer.dll"
/// "analyzers/dotnet/roslyn4.0/analyzer.dll"
///
/// When the <paramref name="compilerApiVersion"/> is 'roslyn3.9', only the assets
/// in the folder with the highest applicable compiler version are picked.
/// In this case,
///
/// "analyzers/dotnet/roslyn3.8/analyzer.dll"
///
/// will be picked, and the other analyzer assets will be excluded.
/// </remarks>
private class AnalyzerResolver
{
private readonly CacheWriter _cacheWriter;
private readonly string? _compilerNameSearchString;
private readonly Version? _compilerVersion;
private Dictionary<(string, NuGetVersion), LockFileTargetLibrary>? _targetLibraries;
private List<(string, LockFileLibrary, Version)>? _potentialAnalyzers;
private Version _maxApplicableVersion;
private Dictionary<(string, NuGetVersion), LockFileTargetLibrary> TargetLibraries =>
_targetLibraries ??=
_cacheWriter._compileTimeTarget.Libraries.ToDictionary(l => (l.Name, l.Version), new LibraryComparer());
public AnalyzerResolver(CacheWriter cacheWriter)
{
_cacheWriter = cacheWriter;
if (ParseCompilerApiVersion(_cacheWriter._task.CompilerApiVersion, out ReadOnlyMemory<char> compilerName, out Version compilerVersion))
{
#if NET
_compilerNameSearchString = string.Concat("/".AsSpan(), compilerName.Span);
#else
_compilerNameSearchString = "/" + compilerName;
#endif
_compilerVersion = compilerVersion;
}
}
public void AddFile(string file, LockFileLibrary library)
{
if (NuGetUtils.IsApplicableAnalyzer(file, _cacheWriter._task.ProjectLanguage))
{
if (IsFileCompilerVersionSpecific(file, out Version fileCompilerVersion))
{
if (fileCompilerVersion > _compilerVersion)
{
// version is too high - skip this file
return;
}
_potentialAnalyzers ??= new List<(string, LockFileLibrary, Version)>();
_potentialAnalyzers.Add((file, library, fileCompilerVersion));
if (_maxApplicableVersion == null || fileCompilerVersion > _maxApplicableVersion)
{
_maxApplicableVersion = fileCompilerVersion;
}
}
else
{
// if this file isn't specific to a compiler version, just write it directly
WriteAnalyzer(file, library);
}
}
}
private bool IsFileCompilerVersionSpecific(string file, out Version fileCompilerVersion)
{
fileCompilerVersion = null;
if (_compilerNameSearchString == null)
{
// unable to tell if this file is specific to a compiler version
return false;
}
int compilerNameStart = file.IndexOf(_compilerNameSearchString);
if (compilerNameStart == -1)
{