forked from dotnet/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DependencyContextBuilder.cs
891 lines (768 loc) · 38 KB
/
DependencyContextBuilder.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using Microsoft.Build.Framework;
using Microsoft.Extensions.DependencyModel;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectModel;
using NuGet.RuntimeModel;
using NuGet.Versioning;
namespace Microsoft.NET.Build.Tasks
{
internal class DependencyContextBuilder
{
private readonly SingleProjectInfo _mainProjectInfo;
private readonly bool _includeRuntimeFileVersions;
private IEnumerable<ReferenceInfo> _referenceAssemblies;
private IEnumerable<ReferenceInfo> _directReferences;
private IEnumerable<ReferenceInfo> _dependencyReferences;
private Dictionary<string, List<ReferenceInfo>> _compileReferences;
private Dictionary<string, List<ResolvedFile>> _resolvedNuGetFiles;
private Dictionary<string, SingleProjectInfo> _referenceProjectInfos;
private Dictionary<string, List<RuntimePackAssetInfo>> _runtimePackAssets;
private CompilationOptions _compilationOptions;
private string _referenceAssembliesPath;
private Dictionary<PackageIdentity, string> _filteredPackages;
private bool _includeMainProjectInDepsFile = true;
private readonly Dictionary<string, DependencyLibrary> _dependencyLibraries;
private readonly Dictionary<string, List<LibraryDependency>> _libraryDependencies;
private readonly List<string> _mainProjectDependencies;
private readonly HashSet<PackageIdentity> _packagesToBeFiltered;
private readonly bool _isFrameworkDependent;
private readonly string _platformLibrary;
private readonly string _dotnetFrameworkName;
private readonly string _runtimeIdentifier;
private readonly bool _isPortable;
private readonly HashSet<string> _usedLibraryNames;
private readonly RuntimeGraph _runtimeGraph;
private Dictionary<ReferenceInfo, string> _referenceLibraryNames;
// This resolver is only used for building file names, so that base path is not required.
private readonly VersionFolderPathResolver _versionFolderPathResolver = new(rootPath: null);
private const string NetCorePlatformLibrary = "Microsoft.NETCore.App";
public DependencyContextBuilder(SingleProjectInfo mainProjectInfo, bool includeRuntimeFileVersions, RuntimeGraph runtimeGraph, ProjectContext projectContext, LockFileLookup libraryLookup)
{
_mainProjectInfo = mainProjectInfo;
_includeRuntimeFileVersions = includeRuntimeFileVersions;
_runtimeGraph = runtimeGraph;
_dependencyLibraries = projectContext.LockFileTarget.Libraries
.Select(lockFileTargetLibrary =>
{
var dependencyLibrary = new DependencyLibrary(lockFileTargetLibrary.Name, lockFileTargetLibrary.Version, lockFileTargetLibrary.Type);
LockFileLibrary library;
if (libraryLookup.TryGetLibrary(lockFileTargetLibrary, out library))
{
dependencyLibrary.Sha512 = library.Sha512;
dependencyLibrary.Path = library.Path;
dependencyLibrary.MSBuildProject = library.MSBuildProject;
}
return dependencyLibrary;
}).ToDictionary(d => d.Name, StringComparer.OrdinalIgnoreCase);
_libraryDependencies = new Dictionary<string, List<LibraryDependency>>(StringComparer.OrdinalIgnoreCase);
foreach (var library in projectContext.LockFileTarget.Libraries)
{
_libraryDependencies[library.Name] = library.Dependencies
.Select(d => new LibraryDependency()
{
Name = d.Id,
MinVersion = d.VersionRange.MinVersion
}).ToList();
}
_mainProjectDependencies = projectContext.GetTopLevelDependencies().ToList();
_packagesToBeFiltered = projectContext.PackagesToBeFiltered;
_isFrameworkDependent = projectContext.IsFrameworkDependent;
_platformLibrary = projectContext.PlatformLibrary?.Name;
_dotnetFrameworkName = projectContext.LockFileTarget.TargetFramework.DotNetFrameworkName;
_runtimeIdentifier = projectContext.LockFileTarget.RuntimeIdentifier;
_isPortable = projectContext.IsPortable;
_usedLibraryNames = new HashSet<string>(_dependencyLibraries.Keys, StringComparer.OrdinalIgnoreCase);
}
public DependencyContextBuilder(
SingleProjectInfo mainProjectInfo,
bool includeRuntimeFileVersions,
ITaskItem[] runtimeFrameworks,
string runtimeIdentifier,
bool isSelfContained,
string platformLibraryName,
string targetFramework)
{
_mainProjectInfo = mainProjectInfo;
_includeRuntimeFileVersions = includeRuntimeFileVersions;
_isFrameworkDependent = LockFileExtensions.IsFrameworkDependent(
runtimeFrameworks,
isSelfContained,
runtimeIdentifier,
string.IsNullOrWhiteSpace(platformLibraryName));
_isPortable = _isFrameworkDependent && string.IsNullOrEmpty(_runtimeIdentifier);
if (_isFrameworkDependent != true || _isPortable != true)
{
throw new ArgumentException(
$"{nameof(DependencyContextBuilder)} Does not support non FrameworkDependent without assetfile. " +
$"runtimeFrameworks: {string.Join(",", runtimeFrameworks.Select(r => r.ItemSpec))} " +
$"isSelfContained: {isSelfContained} " +
$"runtimeIdentifier: {runtimeIdentifier} " +
$"platformLibraryName: {platformLibraryName}");
}
_platformLibrary = platformLibraryName;
// NOTE: This uses the TargetFramework (ie "net5.0") as the deps.json runtimeTarget name, instead of
// the TargetFrameworkMoniker (ie ".NETCoreApp,Version=v5.0"), which is normally used.
//
// This constructor should only be used for C++/CLI, and is used because PackageReference isn't
// currently supported in that context so there is no assets file to read from.
//
// Using the TargetFramework instead should have minimal impact.
_dotnetFrameworkName = targetFramework;
_runtimeIdentifier = runtimeIdentifier;
_dependencyLibraries = new Dictionary<string, DependencyLibrary>();
_libraryDependencies = new Dictionary<string, List<LibraryDependency>>();
_mainProjectDependencies = new List<string>();
_packagesToBeFiltered = null;
_usedLibraryNames = new HashSet<string>();
}
private bool IncludeCompilationLibraries => _compilationOptions != null;
private Dictionary<ReferenceInfo, string> ReferenceLibraryNames
{
get
{
if (_referenceLibraryNames == null)
{
_referenceLibraryNames = new Dictionary<ReferenceInfo, string>();
}
return _referenceLibraryNames;
}
}
public DependencyContextBuilder WithReferenceAssemblies(IEnumerable<ReferenceInfo> referenceAssemblies)
{
// note: ReferenceAssembly libraries only export compile-time stuff
// since they assume the runtime library is present already
_referenceAssemblies = referenceAssemblies;
return this;
}
public DependencyContextBuilder WithDirectReferences(IEnumerable<ReferenceInfo> directReferences)
{
_directReferences = directReferences;
return this;
}
public DependencyContextBuilder WithDependencyReferences(IEnumerable<ReferenceInfo> dependencyReferences)
{
_dependencyReferences = dependencyReferences;
return this;
}
public DependencyContextBuilder WithCompileReferences(IEnumerable<ReferenceInfo> compileReferences)
{
_compileReferences = new Dictionary<string, List<ReferenceInfo>>(StringComparer.OrdinalIgnoreCase);
foreach (var group in compileReferences.GroupBy(r => r.PackageName, StringComparer.OrdinalIgnoreCase))
{
_compileReferences.Add(group.Key, group.ToList());
}
return this;
}
public DependencyContextBuilder WithResolvedNuGetFiles(IEnumerable<ResolvedFile> resolvedNuGetFiles)
{
_resolvedNuGetFiles = new Dictionary<string, List<ResolvedFile>>(StringComparer.OrdinalIgnoreCase);
foreach (var group in resolvedNuGetFiles.GroupBy(f => f.PackageName, StringComparer.OrdinalIgnoreCase))
{
_resolvedNuGetFiles.Add(group.Key, group.ToList());
}
return this;
}
public DependencyContextBuilder WithReferenceProjectInfos(Dictionary<string, SingleProjectInfo> referenceProjectInfos)
{
_referenceProjectInfos = referenceProjectInfos;
return this;
}
public DependencyContextBuilder WithMainProjectInDepsFile(bool includeMainProjectInDepsFile)
{
_includeMainProjectInDepsFile = includeMainProjectInDepsFile;
return this;
}
public DependencyContextBuilder WithRuntimePackAssets(IEnumerable<RuntimePackAssetInfo> runtimePackAssets)
{
_runtimePackAssets = new Dictionary<string, List<RuntimePackAssetInfo>>();
foreach (var runtimePackGroup in runtimePackAssets.GroupBy(a => a.PackageName))
{
var dependencyLibrary = new DependencyLibrary("runtimepack." + runtimePackGroup.Key,
NuGetVersion.Parse(runtimePackGroup.First().PackageVersion),
"runtimepack");
_dependencyLibraries.Add(dependencyLibrary.Name, dependencyLibrary);
_runtimePackAssets[dependencyLibrary.Name] = runtimePackGroup.ToList();
}
return this;
}
public DependencyContextBuilder WithCompilationOptions(CompilationOptions compilationOptions)
{
_compilationOptions = compilationOptions;
return this;
}
public DependencyContextBuilder WithReferenceAssembliesPath(string referenceAssembliesPath)
{
// if the path is empty, we want to use the original string instead of a single trailing character.
if (string.IsNullOrEmpty(referenceAssembliesPath) ||
referenceAssembliesPath[referenceAssembliesPath.Length - 1] == Path.DirectorySeparatorChar)
{
_referenceAssembliesPath = referenceAssembliesPath;
}
else
{
_referenceAssembliesPath = referenceAssembliesPath + Path.DirectorySeparatorChar;
}
return this;
}
public DependencyContextBuilder WithPackagesThatWereFiltered(Dictionary<PackageIdentity, string> packagesThatWhereFiltered)
{
_filteredPackages = packagesThatWhereFiltered;
return this;
}
public DependencyContext Build(string[] userRuntimeAssemblies = null)
{
CalculateExcludedLibraries();
List<RuntimeLibrary> runtimeLibraries = new();
if (_includeMainProjectInDepsFile)
{
runtimeLibraries.Add(GetProjectRuntimeLibrary());
}
runtimeLibraries.AddRange(GetRuntimePackLibraries());
foreach (var library in _dependencyLibraries.Values
.Where(l => !l.ExcludeFromRuntime && l.Type != "runtimepack"))
{
var runtimeLibrary = GetRuntimeLibrary(library, userRuntimeAssemblies);
if (runtimeLibrary != null)
{
runtimeLibraries.Add(runtimeLibrary);
}
}
var directAndDependencyReferences = _directReferences ?? Enumerable.Empty<ReferenceInfo>();
if (_dependencyReferences != null)
{
directAndDependencyReferences = directAndDependencyReferences.Concat(_dependencyReferences);
}
foreach (var directReference in directAndDependencyReferences)
{
var runtimeLibrary = new RuntimeLibrary(
type: "reference",
name: GetReferenceLibraryName(directReference),
version: directReference.Version,
hash: string.Empty,
runtimeAssemblyGroups: new[] { new RuntimeAssetGroup(string.Empty, new[] { CreateRuntimeFile(directReference.FileName, directReference.FullPath) }) },
nativeLibraryGroups: new RuntimeAssetGroup[] { },
resourceAssemblies: CreateResourceAssemblies(directReference.ResourceAssemblies),
dependencies: Enumerable.Empty<Dependency>(),
path: null,
hashPath: null,
runtimeStoreManifestName: null,
serviceable: false);
runtimeLibraries.Add(runtimeLibrary);
}
List<CompilationLibrary> compilationLibraries = new();
if (IncludeCompilationLibraries)
{
if (_includeMainProjectInDepsFile)
{
var dependencies = GetProjectDependencies();
var projectCompilationLibrary = new CompilationLibrary(
type: "project",
name: _mainProjectInfo.Name,
version: _mainProjectInfo.Version,
hash: string.Empty,
assemblies: new[] { _mainProjectInfo.OutputName },
dependencies: dependencies,
serviceable: false);
compilationLibraries.Add(projectCompilationLibrary);
}
if (_referenceAssemblies != null)
{
foreach (var referenceAssembly in _referenceAssemblies)
{
string resolvedPath;
if (!string.IsNullOrEmpty(_referenceAssembliesPath) &&
referenceAssembly.FullPath?.StartsWith(_referenceAssembliesPath) == true)
{
resolvedPath = referenceAssembly.FullPath.Substring(_referenceAssembliesPath.Length);
}
else
{
resolvedPath = Path.GetFileName(referenceAssembly.FullPath);
}
compilationLibraries.Add(new CompilationLibrary(
type: "referenceassembly",
name: GetReferenceLibraryName(referenceAssembly),
version: referenceAssembly.Version,
hash: string.Empty,
assemblies: new[] { resolvedPath },
dependencies: Enumerable.Empty<Dependency>(),
serviceable: false));
}
}
foreach (var library in _dependencyLibraries.Values
.Where(l => !l.ExcludeFromCompilation && l.Type != "runtimepack"))
{
var compilationLibrary = GetCompilationLibrary(library);
if (compilationLibrary != null)
{
compilationLibraries.Add(compilationLibrary);
}
}
if (_directReferences != null)
{
foreach (var directReference in _directReferences)
{
compilationLibraries.Add(new CompilationLibrary(
type: "reference",
name: GetReferenceLibraryName(directReference),
version: directReference.Version,
hash: string.Empty,
assemblies: new[] { directReference.FileName },
dependencies: Enumerable.Empty<Dependency>(),
serviceable: false));
}
}
}
var targetInfo = new TargetInfo(
_dotnetFrameworkName,
_runtimeIdentifier,
runtimeSignature: string.Empty,
_isPortable);
// Compute the runtime fallback graph
//
// If the input RuntimeGraph is empty, or we're not compiling
// for a specific RID, then an runtime fallback graph is empty
//
// Otherwise, it is the set of all runtimes compatible with (inheriting)
// the target runtime-identifier.
var runtimeFallbackGraph =
(_runtimeGraph == null || _runtimeIdentifier == null) ?
new RuntimeFallbacks[] { } :
_runtimeGraph.Runtimes
.Select(runtimeDict => _runtimeGraph.ExpandRuntime(runtimeDict.Key))
.Where(expansion => expansion.Contains(_runtimeIdentifier))
.Select(expansion => new RuntimeFallbacks(expansion.First(), expansion.Skip(1))); // ExpandRuntime return runtime itself as first item.
return new DependencyContext(
targetInfo,
_compilationOptions ?? CompilationOptions.Default,
compilationLibraries,
runtimeLibraries,
runtimeFallbackGraph);
}
private RuntimeLibrary GetProjectRuntimeLibrary()
{
RuntimeAssetGroup[] runtimeAssemblyGroups = new[] { new RuntimeAssetGroup(string.Empty, _mainProjectInfo.OutputName) };
var dependencies = GetProjectDependencies();
// Runtime pack assets only get added as dependencies to the runtime (not the compile) project
if (_runtimePackAssets != null)
{
foreach (var runtimePackName in _runtimePackAssets.Keys)
{
dependencies.Add(_dependencyLibraries[runtimePackName].Dependency);
}
}
return new RuntimeLibrary(
type: "project",
name: _mainProjectInfo.Name,
version: _mainProjectInfo.Version,
hash: string.Empty,
runtimeAssemblyGroups: runtimeAssemblyGroups,
nativeLibraryGroups: Array.Empty<RuntimeAssetGroup>(),
resourceAssemblies: CreateResourceAssemblies(_mainProjectInfo.ResourceAssemblies),
dependencies: dependencies,
path: null,
hashPath: null,
runtimeStoreManifestName: GetRuntimeStoreManifestName(_mainProjectInfo.Name, _mainProjectInfo.Version),
serviceable: false);
}
private List<Dependency> GetProjectDependencies()
{
List<Dependency> dependencies = new();
foreach (var dependencyName in _mainProjectDependencies)
{
if (_dependencyLibraries.TryGetValue(dependencyName, out var dependencyLibrary))
{
// Include dependency if it would be included either as a runtime or compilation
// (if compilation libraries are being included) library
if (!dependencyLibrary.ExcludeFromRuntime ||
(IncludeCompilationLibraries && !dependencyLibrary.ExcludeFromCompilation))
{
dependencies.Add(dependencyLibrary.Dependency);
}
}
}
var references = _directReferences;
if (IncludeCompilationLibraries && _referenceAssemblies != null)
{
if (references == null)
{
references = _referenceAssemblies;
}
else
{
references = references.Concat(_referenceAssemblies);
}
}
if (references != null)
{
foreach (var directReference in references)
{
dependencies.Add(
new Dependency(
GetReferenceLibraryName(directReference),
directReference.Version));
}
}
return dependencies;
}
private IEnumerable<RuntimeLibrary> GetRuntimePackLibraries()
{
if (_runtimePackAssets == null)
{
return Enumerable.Empty<RuntimeLibrary>();
}
return _runtimePackAssets.Select(runtimePack =>
{
var runtimeAssemblyGroup = new RuntimeAssetGroup(string.Empty,
runtimePack.Value.Where(asset => asset.AssetType == AssetType.Runtime)
.Select(asset => CreateRuntimeFile(asset.DestinationSubPath, asset.SourcePath)));
var nativeLibraryGroup = new RuntimeAssetGroup(string.Empty,
runtimePack.Value.Where(asset => asset.AssetType == AssetType.Native)
.Select(asset => CreateRuntimeFile(asset.DestinationSubPath, asset.SourcePath)));
return new RuntimeLibrary(
type: "runtimepack",
name: runtimePack.Key,
version: runtimePack.Value.First().PackageVersion,
hash: string.Empty,
runtimeAssemblyGroups: new[] { runtimeAssemblyGroup },
nativeLibraryGroups: new[] { nativeLibraryGroup },
resourceAssemblies: Enumerable.Empty<ResourceAssembly>(),
dependencies: Enumerable.Empty<Dependency>(),
serviceable: false);
});
}
private RuntimeLibrary GetRuntimeLibrary(DependencyLibrary library, string[] userRuntimeAssemblies)
{
GetCommonLibraryProperties(library,
out string hash,
out HashSet<Dependency> libraryDependencies,
out bool serviceable,
out string path,
out string hashPath,
out SingleProjectInfo referenceProjectInfo);
if (referenceProjectInfo is UnreferencedProjectInfo)
{
// unreferenced ProjectInfos will be added later as simple dll dependencies
return null;
}
List<RuntimeAssetGroup> runtimeAssemblyGroups = new();
List<RuntimeAssetGroup> nativeLibraryGroups = new();
List<ResourceAssembly> resourceAssemblies = new();
if (library.Type == "project" && !(referenceProjectInfo is UnreferencedProjectInfo))
{
var fileName = Path.GetFileNameWithoutExtension(library.Path);
var assemblyPath = userRuntimeAssemblies?.FirstOrDefault(p => Path.GetFileNameWithoutExtension(p).Equals(fileName));
runtimeAssemblyGroups.Add(new RuntimeAssetGroup(string.Empty,
[ new RuntimeFile(
referenceProjectInfo.OutputName,
library.Version.ToString(),
assemblyPath is null || !File.Exists(assemblyPath) ? string.Empty : FileVersionInfo.GetVersionInfo(assemblyPath).FileVersion)
]));
resourceAssemblies.AddRange(referenceProjectInfo.ResourceAssemblies
.Select(r => new ResourceAssembly(r.RelativePath, r.Culture)));
}
else
{
if (_resolvedNuGetFiles != null && _resolvedNuGetFiles.TryGetValue(library.Name, out var resolvedNuGetFiles))
{
var runtimeFiles = resolvedNuGetFiles.Where(f => f.Asset == AssetType.Runtime &&
!f.IsRuntimeTarget);
runtimeAssemblyGroups.Add(new RuntimeAssetGroup(string.Empty,
runtimeFiles.Select(CreateRuntimeFile)));
var nativeFiles = resolvedNuGetFiles.Where(f => f.Asset == AssetType.Native &&
!f.IsRuntimeTarget);
nativeLibraryGroups.Add(new RuntimeAssetGroup(string.Empty,
nativeFiles.Select(CreateRuntimeFile)));
var resourceFiles = resolvedNuGetFiles.Where(f => f.Asset == AssetType.Resources &&
!f.IsRuntimeTarget);
resourceAssemblies.AddRange(resourceFiles.Select(f => new ResourceAssembly(f.PathInPackage, f.Culture)));
var runtimeTargets = resolvedNuGetFiles.Where(f => f.IsRuntimeTarget)
.GroupBy(f => f.RuntimeIdentifier);
foreach (var runtimeIdentifierGroup in runtimeTargets)
{
var managedRuntimeTargetsFiles = runtimeIdentifierGroup.Where(f => f.Asset == AssetType.Runtime).ToList();
if (managedRuntimeTargetsFiles.Any())
{
runtimeAssemblyGroups.Add(new RuntimeAssetGroup(runtimeIdentifierGroup.Key,
managedRuntimeTargetsFiles.Select(CreateRuntimeFile)));
}
var nativeRuntimeTargetsFiles = runtimeIdentifierGroup.Where(f => f.Asset == AssetType.Native).ToList();
if (nativeRuntimeTargetsFiles.Any())
{
nativeLibraryGroups.Add(new RuntimeAssetGroup(runtimeIdentifierGroup.Key,
nativeRuntimeTargetsFiles.Select(CreateRuntimeFile)));
}
}
}
}
var runtimeLibrary = new RuntimeLibrary(
type: library.Type,
name: library.Name,
version: library.Version.ToString(),
hash: hash,
runtimeAssemblyGroups: runtimeAssemblyGroups,
nativeLibraryGroups: nativeLibraryGroups,
resourceAssemblies: resourceAssemblies,
dependencies: libraryDependencies,
path: path,
hashPath: hashPath,
runtimeStoreManifestName: GetRuntimeStoreManifestName(library.Name, library.Version.ToString()),
serviceable: serviceable);
return runtimeLibrary;
}
private CompilationLibrary GetCompilationLibrary(DependencyLibrary library)
{
GetCommonLibraryProperties(library,
out string hash,
out HashSet<Dependency> libraryDependencies,
out bool serviceable,
out string path,
out string hashPath,
out SingleProjectInfo referenceProjectInfo);
List<string> assemblies = new();
if (library.Type == "project" && !(referenceProjectInfo is UnreferencedProjectInfo))
{
assemblies.Add(referenceProjectInfo.OutputName);
}
else if (_compileReferences != null && _compileReferences.TryGetValue(library.Name, out var compileReferences))
{
foreach (var compileReference in compileReferences)
{
assemblies.Add(compileReference.PathInPackage);
}
}
return new CompilationLibrary(
type: library.Type,
name: library.Name,
version: library.Version.ToString(),
hash,
assemblies,
libraryDependencies,
serviceable,
path,
hashPath);
}
private void GetCommonLibraryProperties(DependencyLibrary library,
out string hash,
out HashSet<Dependency> dependencies,
out bool serviceable,
out string path,
out string hashPath,
out SingleProjectInfo referenceProjectInfo)
{
serviceable = true;
referenceProjectInfo = null;
dependencies = new HashSet<Dependency>();
List<LibraryDependency> libraryDependencies;
if (_libraryDependencies.TryGetValue(library.Name, out libraryDependencies))
{
foreach (var dependency in libraryDependencies)
{
if (_dependencyLibraries.TryGetValue(dependency.Name, out var libraryDependency))
{
if (!libraryDependency.ExcludeFromRuntime ||
(!libraryDependency.ExcludeFromCompilation && IncludeCompilationLibraries))
{
dependencies.Add(libraryDependency.Dependency);
}
}
}
}
hash = string.Empty;
path = null;
hashPath = null;
if (library.Type == "package")
{
// TEMPORARY: All packages are serviceable in RC2
// See https://github.com/dotnet/cli/issues/2569
serviceable = true;
if (!string.IsNullOrEmpty(library.Sha512))
{
hash = "sha512-" + library.Sha512;
hashPath = _versionFolderPathResolver.GetHashFileName(library.Name, library.Version);
}
path = library.Path;
}
else if (library.Type == "project")
{
serviceable = false;
referenceProjectInfo = GetProjectInfo(library);
foreach (var dependencyReference in referenceProjectInfo.DependencyReferences)
{
dependencies.Add(
new Dependency(
GetReferenceLibraryName(dependencyReference),
dependencyReference.Version));
}
}
}
private RuntimeFile CreateRuntimeFile(ResolvedFile resolvedFile)
{
string relativePath = resolvedFile.PathInPackage;
if (string.IsNullOrEmpty(relativePath))
{
relativePath = resolvedFile.DestinationSubPath;
}
return CreateRuntimeFile(relativePath, resolvedFile.SourcePath);
}
private RuntimeFile CreateRuntimeFile(string path, string fullPath)
{
if (_includeRuntimeFileVersions)
{
string fileVersion = FileUtilities.GetFileVersion(fullPath).ToString();
string assemblyVersion = FileUtilities.TryGetAssemblyVersion(fullPath)?.ToString();
return new RuntimeFile(path, assemblyVersion, fileVersion);
}
else
{
return new RuntimeFile(path, null, null);
}
}
private static IEnumerable<ResourceAssembly> CreateResourceAssemblies(IEnumerable<ResourceAssemblyInfo> resourceAssemblyInfos)
{
return resourceAssemblyInfos
.Select(r => new ResourceAssembly(r.RelativePath, r.Culture));
}
private SingleProjectInfo GetProjectInfo(DependencyLibrary library)
{
string projectPath = library.MSBuildProject;
if (string.IsNullOrEmpty(projectPath))
{
throw new BuildErrorException(Strings.CannotFindProjectInfo, library.Name);
}
string mainProjectDirectory = Path.GetDirectoryName(_mainProjectInfo.ProjectPath);
string fullProjectPath = Path.GetFullPath(Path.Combine(mainProjectDirectory, projectPath));
SingleProjectInfo referenceProjectInfo = null;
if (_referenceProjectInfos?.TryGetValue(fullProjectPath, out referenceProjectInfo) != true ||
referenceProjectInfo == null)
{
return UnreferencedProjectInfo.Default;
}
return referenceProjectInfo;
}
private void CalculateExcludedLibraries()
{
Dictionary<string, DependencyLibrary> libraries = _dependencyLibraries;
HashSet<string> runtimeExclusionList = new(StringComparer.OrdinalIgnoreCase);
if (_isFrameworkDependent && !string.IsNullOrEmpty(_platformLibrary))
{
// Exclude platform library and dependencies.
runtimeExclusionList.Add(_platformLibrary);
Stack<LibraryDependency> dependenciesToWalk = new(_libraryDependencies[_platformLibrary]);
// If the platform library is not Microsoft.NETCore.App, treat it as an implicit dependency.
// This makes it so Microsoft.AspNet.* 2.x platforms also exclude Microsoft.NETCore.App files.
if (!string.Equals(_platformLibrary, NetCorePlatformLibrary, StringComparison.OrdinalIgnoreCase))
{
if (_dependencyLibraries.TryGetValue(NetCorePlatformLibrary, out var netCoreDependencyLibrary))
{
dependenciesToWalk.Push(new LibraryDependency()
{
Name = netCoreDependencyLibrary.Name,
MinVersion = netCoreDependencyLibrary.Version
});
}
}
while (dependenciesToWalk.Any())
{
var dependency = dependenciesToWalk.Pop();
if (runtimeExclusionList.Contains(dependency.Name))
{
continue;
}
// Resolved version of library has to match dependency version exactly, so that we
// don't exclude newer versions of libraries that are part of the platform
if (_dependencyLibraries[dependency.Name].Version == dependency.MinVersion)
{
runtimeExclusionList.Add(dependency.Name);
foreach (var newDependency in _libraryDependencies[dependency.Name])
{
dependenciesToWalk.Push(newDependency);
}
}
}
}
if (_packagesToBeFiltered != null)
{
foreach (var packageToFilter in _packagesToBeFiltered)
{
if (_dependencyLibraries.TryGetValue(packageToFilter.Id, out var library))
{
if (library.Type == "package" &&
_dependencyLibraries[packageToFilter.Id].Version == packageToFilter.Version)
{
runtimeExclusionList.Add(packageToFilter.Id);
}
}
}
}
foreach (var packageToExcludeFromRuntime in runtimeExclusionList)
{
_dependencyLibraries[packageToExcludeFromRuntime].ExcludeFromRuntime = true;
}
}
private string GetReferenceLibraryName(ReferenceInfo reference)
{
if (!ReferenceLibraryNames.TryGetValue(reference, out string name))
{
// Reference names can conflict with PackageReference names, so
// ensure that the Reference names are unique when creating libraries
name = GetUniqueReferenceName(reference.Name);
ReferenceLibraryNames.Add(reference, name);
_usedLibraryNames.Add(name);
}
return name;
}
private string GetUniqueReferenceName(string name)
{
if (_usedLibraryNames.Contains(name))
{
string startingName = $"{name}.Reference";
name = startingName;
int suffix = 1;
while (_usedLibraryNames.Contains(name))
{
name = $"{startingName}{suffix++}";
}
}
return name;
}
private string GetRuntimeStoreManifestName(string packageName, string packageVersion)
{
string runtimeStoreManifestName = null;
if (_filteredPackages != null && _filteredPackages.Any())
{
var pkg = new PackageIdentity(packageName, NuGetVersion.Parse(packageVersion));
_filteredPackages?.TryGetValue(pkg, out runtimeStoreManifestName);
}
return runtimeStoreManifestName;
}
private class DependencyLibrary
{
public string Name { get; }
public NuGetVersion Version { get; }
public string Type { get; }
public Dependency Dependency { get; }
public string Sha512 { get; set; }
public string Path { get; set; }
public string MSBuildProject { get; set; }
public bool ExcludeFromRuntime { get; set; }
public bool ExcludeFromCompilation { get; set; }
public DependencyLibrary(string name, NuGetVersion version, string type)
{
Name = name;
Version = version;
Type = type;
Dependency = new Dependency(name, version.ToString());
}
}
private struct LibraryDependency
{
public string Name { get; set; }
public NuGetVersion MinVersion { get; set; }
}
}
}