-
Notifications
You must be signed in to change notification settings - Fork 748
Expand file tree
/
Copy pathLockFileUtils.cs
More file actions
1109 lines (960 loc) · 47.9 KB
/
LockFileUtils.cs
File metadata and controls
1109 lines (960 loc) · 47.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable disable
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using NuGet.Client;
using NuGet.Common;
using NuGet.ContentModel;
using NuGet.DependencyResolver;
using NuGet.Frameworks;
using NuGet.LibraryModel;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectModel;
using NuGet.Repositories;
using NuGet.Shared;
using NuGet.Versioning;
namespace NuGet.Commands
{
public static class LockFileUtils
{
public static readonly string LIBANY = nameof(LIBANY);
public static LockFileTargetLibrary CreateLockFileTargetLibrary(
LockFileLibrary library,
LocalPackageInfo package,
RestoreTargetGraph targetGraph,
LibraryIncludeFlags dependencyType)
{
var (lockFileTargetLibrary, _, _, _) = CreateLockFileTargetLibrary(
aliases: null,
library,
package,
targetGraph,
dependencyType: dependencyType,
targetFrameworkOverride: null,
dependencies: null,
cache: new LockFileBuilderCache());
return lockFileTargetLibrary;
}
/// <summary>
/// Create a lock file target library for the given <paramref name="library"/>
/// </summary>
/// <param name="aliases">When an alias is specified, all assemblies coming from the library will need to be referenced with an alias.</param>
/// <param name="library">The lock file library, expected to be for the equivalent package as <paramref name="library"/> and <paramref name="package"/>. </param>
/// <param name="package">The local package info.</param>
/// <param name="targetGraph">The target graph for which the asset selection needs to happen.</param>
/// <param name="dependencyType">The resolved dependency type.</param>
/// <param name="targetFrameworkOverride">The original framework if the asset selection is happening for a fallback framework.</param>
/// <param name="dependencies">The dependencies of this package.</param>
/// <param name="cache">The lock file build cache.</param>
/// <returns>The LockFileTargetLibrary, whether a fallback framework criteria was used to select it, the framework selected for compile assets, and the framework selected for runtime assets.</returns>
internal static (LockFileTargetLibrary, bool, NuGetFramework, NuGetFramework) CreateLockFileTargetLibrary(
string aliases,
LockFileLibrary library,
LocalPackageInfo package,
RestoreTargetGraph targetGraph,
LibraryIncludeFlags dependencyType,
NuGetFramework targetFrameworkOverride,
List<LibraryDependency> dependencies,
LockFileBuilderCache cache)
{
var runtimeIdentifier = targetGraph.RuntimeIdentifier;
var framework = targetFrameworkOverride ?? targetGraph.Framework;
return cache.GetLockFileTargetLibrary(targetGraph, framework, package, aliases, dependencyType, dependencies,
() =>
{
LockFileTargetLibrary lockFileLib = null;
NuGetFramework compileAssetFramework = null;
NuGetFramework runtimeAssetFramework = null;
// This will throw an appropriate error if the nuspec is missing
var nuspec = package.Nuspec;
List<(List<SelectionCriteria> orderedCriteria, bool fallbackUsed)> orderedCriteriaSets = cache.GetLabeledSelectionCriteria(targetGraph, framework);
var contentItems = cache.GetContentItems(library, package);
var packageTypes = nuspec.GetPackageTypes().AsList();
bool fallbackUsed = false;
for (var i = 0; i < orderedCriteriaSets.Count; i++)
{
(lockFileLib, compileAssetFramework, runtimeAssetFramework) = CreateLockFileTargetLibrary(aliases, library, package, targetGraph.Conventions, dependencyType,
framework, runtimeIdentifier, contentItems, nuspec, packageTypes, orderedCriteriaSets[i].orderedCriteria);
// Check if compatible assets were found.
// If no compatible assets were found and this is the last check
// continue on with what was given, this will fail in the normal
// compat verification.
if (CompatibilityChecker.HasCompatibleAssets(lockFileLib))
{
fallbackUsed = orderedCriteriaSets[i].fallbackUsed;
// Stop when compatible assets are found.
break;
}
}
// Add dependencies
AddDependencies(dependencies, lockFileLib, framework, nuspec);
// Exclude items
ExcludeItems(lockFileLib, dependencyType);
lockFileLib.Freeze();
return (lockFileLib, fallbackUsed, compileAssetFramework, runtimeAssetFramework);
});
}
/// <summary>
/// Create an ordered criteria list in order, based on the framework and runtime identifier provided.
/// The boolean indicates whether the criteria is for a fallback version of the framework or not.
/// </summary>
internal static List<(List<SelectionCriteria>, bool)> CreateOrderedCriteriaSets(ManagedCodeConventions codeConventions, NuGetFramework framework, string runtimeIdentifier)
{
// Create an ordered list of selection criteria. Each will be applied, if the result is empty
// fallback frameworks from "imports" will be tried.
// These are only used for framework/RID combinations where content model handles everything.
// AssetTargetFallback and DualCompatbiility frameworks will provide multiple criteria since all assets need to be
// evaluated before selecting the TFM to use.
var orderedCriteriaSets = new List<(List<SelectionCriteria>, bool)>(1);
var assetTargetFallback = framework as AssetTargetFallbackFramework;
if (assetTargetFallback != null)
{
// Add the root project framework first.
orderedCriteriaSets.Add((CreateCriteria(codeConventions, assetTargetFallback.RootFramework, runtimeIdentifier), false));
// Add the secondary framework if dual compatibility framework.
if (assetTargetFallback.RootFramework is DualCompatibilityFramework dualCompatibilityFramework)
{
orderedCriteriaSets.Add((CreateCriteria(codeConventions, dualCompatibilityFramework.SecondaryFramework, runtimeIdentifier), false));
}
// Add all fallbacks in order.
orderedCriteriaSets.AddRange(assetTargetFallback.Fallback.Select(e => (CreateCriteria(codeConventions, e, runtimeIdentifier), true)));
}
else
{
// Add the current framework.
orderedCriteriaSets.Add((CreateCriteria(codeConventions, framework, runtimeIdentifier), false));
if (framework is DualCompatibilityFramework dualCompatibilityFramework)
{
orderedCriteriaSets.Add((CreateCriteria(codeConventions, dualCompatibilityFramework.SecondaryFramework, runtimeIdentifier), false));
}
}
return orderedCriteriaSets;
}
private static void ApplyAliases(string aliases, LockFileItem item)
{
if (!string.IsNullOrEmpty(aliases))
{
item.Properties.Add(LockFileItem.AliasesProperty, aliases);
}
}
/// <summary>
/// Populate assets for a <see cref="LockFileLibrary"/>.
/// </summary>
internal static (LockFileTargetLibrary lockFileLib, NuGetFramework compileAssetFramework, NuGetFramework runtimeAssetFramework) CreateLockFileTargetLibrary(
string aliases,
LockFileLibrary library,
LocalPackageInfo package,
ManagedCodeConventions managedCodeConventions,
LibraryIncludeFlags dependencyType,
NuGetFramework framework,
string runtimeIdentifier,
ContentItemCollection contentItems,
NuspecReader nuspec,
IList<PackageType> packageTypes,
List<SelectionCriteria> orderedCriteria)
{
LockFileTargetLibrary lockFileLib = new LockFileTargetLibrary()
{
Name = library.Name,
Version = library.Version,
Type = LibraryType.Package,
PackageType = packageTypes
};
// Add framework references for desktop projects.
AddFrameworkReferences(lockFileLib, framework, nuspec);
// Compile
// Set-up action to update the compile time items.
Action<LockFileItem> applyAliases = (item) => ApplyAliases(aliases, item);
// ref takes precedence over lib
lockFileLib.CompileTimeAssemblies = GetLockFileItems(
orderedCriteria,
contentItems,
applyAliases,
out NuGetFramework compileFramework,
managedCodeConventions.Patterns.CompileRefAssemblies,
managedCodeConventions.Patterns.CompileLibAssemblies);
// Runtime
lockFileLib.RuntimeAssemblies = GetLockFileItems(
orderedCriteria,
contentItems,
additionalAction: null,
out NuGetFramework runtimeFramework,
managedCodeConventions.Patterns.RuntimeAssemblies);
// Embed
lockFileLib.EmbedAssemblies = GetLockFileItems(
orderedCriteria,
contentItems,
managedCodeConventions.Patterns.EmbedAssemblies);
// Resources
lockFileLib.ResourceAssemblies = GetLockFileItems(
orderedCriteria,
contentItems,
managedCodeConventions.Patterns.ResourceAssemblies);
// Native
lockFileLib.NativeLibraries = GetLockFileItems(
orderedCriteria,
contentItems,
managedCodeConventions.Patterns.NativeLibraries);
// Add MSBuild files
AddMSBuildAssets(library.Name, managedCodeConventions, lockFileLib, orderedCriteria, contentItems);
// Add content files
AddContentFiles(managedCodeConventions, lockFileLib, framework, contentItems, nuspec);
// Runtime targets
// These are applied only to non-RID target graphs.
// They are not used for compatibility checks.
AddRuntimeTargets(managedCodeConventions, dependencyType, lockFileLib, framework, runtimeIdentifier, contentItems);
// COMPAT: Support lib/contract so older packages can be consumed
ApplyLibContract(package, lockFileLib, framework, contentItems);
// Apply filters from the <references> node in the nuspec
ApplyReferenceFilter(lockFileLib, framework, nuspec);
return (lockFileLib, compileFramework, runtimeFramework);
}
private static void AddMSBuildAssets(
string libraryName,
ManagedCodeConventions managedCodeConventions,
LockFileTargetLibrary lockFileLib,
List<SelectionCriteria> orderedCriteria,
ContentItemCollection contentItems)
{
// Build Transitive
var btGroup = GetLockFileItems(
orderedCriteria,
contentItems,
managedCodeConventions.Patterns.MSBuildTransitiveFiles);
var filteredBTGroup = GetBuildItemsForPackageId(btGroup, libraryName);
lockFileLib.Build.AddRange(filteredBTGroup);
// Build
var buildGroup = GetLockFileItems(
orderedCriteria,
contentItems,
managedCodeConventions.Patterns.MSBuildFiles);
// filter any build asset already being added as part of build transitive
// PERF: Avoid using LINQ in this path.
foreach (var buildItem in GetBuildItemsForPackageId(buildGroup, libraryName))
{
bool found = false;
foreach (var btItem in filteredBTGroup)
{
if (Path.GetFileName(btItem.Path).Equals(Path.GetFileName(buildItem.Path), StringComparison.OrdinalIgnoreCase))
{
found = true;
break;
}
}
if (!found)
{
lockFileLib.Build.Add(buildItem);
}
}
// Build multi targeting
var buildMultiTargetingGroup = GetLockFileItems(
orderedCriteria,
contentItems,
managedCodeConventions.Patterns.MSBuildMultiTargetingFiles);
lockFileLib.BuildMultiTargeting.AddRange(GetBuildItemsForPackageId(buildMultiTargetingGroup, libraryName));
}
private static void AddContentFiles(ManagedCodeConventions managedCodeConventions, LockFileTargetLibrary lockFileLib, NuGetFramework framework, ContentItemCollection contentItems, NuspecReader nuspec)
{
// content v2 items
List<ContentItemGroup> contentFileGroups = new();
contentItems.PopulateItemGroups(managedCodeConventions.Patterns.ContentFiles, contentFileGroups);
if (contentFileGroups.Count > 0)
{
// Multiple groups can match the same framework, find all of them
var contentFileGroupsForFramework = ContentFileUtils.GetContentGroupsForFramework(
framework,
contentFileGroups);
lockFileLib.ContentFiles = ContentFileUtils.GetContentFileGroup(
nuspec,
contentFileGroupsForFramework);
}
}
/// <summary>
/// Runtime targets
/// These are applied only to non-RID target graphs.
/// They are not used for compatibility checks.
/// </summary>
private static void AddRuntimeTargets(
ManagedCodeConventions managedCodeConventions,
LibraryIncludeFlags dependencyType,
LockFileTargetLibrary lockFileLib,
NuGetFramework framework,
string runtimeIdentifier,
ContentItemCollection contentItems)
{
if (string.IsNullOrEmpty(runtimeIdentifier))
{
// Runtime targets contain all the runtime specific assets
// that could be contained in the runtime specific target graphs.
// These items are contained in a flat list and have additional properties
// for the RID and lock file section the assembly would belong to.
var runtimeTargetItems = new List<LockFileRuntimeTarget>();
// Runtime
runtimeTargetItems.AddRange(GetRuntimeTargetLockFileItems(
contentItems,
framework,
dependencyType,
LibraryIncludeFlags.Runtime,
managedCodeConventions.Patterns.RuntimeAssemblies,
"runtime"));
// Resource
runtimeTargetItems.AddRange(GetRuntimeTargetLockFileItems(
contentItems,
framework,
dependencyType,
LibraryIncludeFlags.Runtime,
managedCodeConventions.Patterns.ResourceAssemblies,
"resource"));
// Native
runtimeTargetItems.AddRange(GetRuntimeTargetLockFileItems(
contentItems,
framework,
dependencyType,
LibraryIncludeFlags.Native,
managedCodeConventions.Patterns.NativeLibraries,
"native"));
lockFileLib.RuntimeTargets = runtimeTargetItems;
}
}
/// <summary>
/// Add framework references.
/// </summary>
private static void AddFrameworkReferences(LockFileTargetLibrary lockFileLib, NuGetFramework framework, NuspecReader nuspec)
{
// Exclude framework references for package based frameworks.
if (!framework.IsPackageBased)
{
var frameworkAssemblies = nuspec.GetFrameworkAssemblyGroups().GetNearest(framework);
if (frameworkAssemblies != null)
{
foreach (var assemblyReference in frameworkAssemblies.Items)
{
lockFileLib.FrameworkAssemblies.Add(assemblyReference);
}
}
}
// Related to: FrameworkReference item, added first in .NET Core 3.0
var frameworkRef = nuspec.GetFrameworkRefGroups().GetNearest(framework);
if (frameworkRef != null)
{
lockFileLib.FrameworkReferences.AddRange(frameworkRef.FrameworkReferences.Select(e => e.Name));
}
}
/// <summary>
/// Apply filters from the references node in the nuspec.
/// </summary>
private static void ApplyReferenceFilter(LockFileTargetLibrary lockFileLib, NuGetFramework framework, NuspecReader nuspec)
{
if (lockFileLib.CompileTimeAssemblies.Count > 0 || lockFileLib.RuntimeAssemblies.Count > 0)
{
var groups = nuspec.GetReferenceGroups().ToList();
if (groups.Count > 0)
{
var referenceSet = groups.GetNearest(framework);
if (referenceSet != null)
{
var referenceFilter = new HashSet<string>(referenceSet.Items, StringComparer.OrdinalIgnoreCase);
// Remove anything that starts with "lib/" and is NOT specified in the reference filter.
// runtimes/* is unaffected (it doesn't start with lib/)
lockFileLib.RuntimeAssemblies = lockFileLib.RuntimeAssemblies.Where(p => !p.Path.StartsWith("lib/", StringComparison.Ordinal) || referenceFilter.Contains(Path.GetFileName(p.Path))).ToList();
lockFileLib.CompileTimeAssemblies = lockFileLib.CompileTimeAssemblies.Where(p => !p.Path.StartsWith("lib/", StringComparison.Ordinal) || referenceFilter.Contains(Path.GetFileName(p.Path))).ToList();
}
}
}
}
/// <summary>
/// COMPAT: Support lib/contract so older packages can be consumed
/// </summary>
private static void ApplyLibContract(LocalPackageInfo package, LockFileTargetLibrary lockFileLib, NuGetFramework framework, ContentItemCollection contentItems)
{
if (contentItems.HasContract && lockFileLib.RuntimeAssemblies.Count > 0 && !framework.IsDesktop())
{
var contractPath = "lib/contract/" + package.Id + ".dll";
if (package.Files.Any(path => path == contractPath))
{
lockFileLib.CompileTimeAssemblies.Clear();
lockFileLib.CompileTimeAssemblies.Add(new LockFileItem(contractPath));
}
}
}
private static void AddDependencies(IEnumerable<LibraryDependency> dependencies, LockFileTargetLibrary lockFileLib, NuGetFramework framework, NuspecReader nuspec)
{
if (dependencies == null)
{
// DualCompatibilityFramework & AssetFallbackFramework does not apply to dependencies.
// Convert it to a fallback framework if needed.
NuGetFramework currentFramework = framework;
if (framework is AssetTargetFallbackFramework atf)
{
currentFramework = atf.AsFallbackFramework();
}
else if (framework is DualCompatibilityFramework mcf)
{
currentFramework = mcf.AsFallbackFramework();
}
var dependencySet = nuspec
.GetDependencyGroups()
.GetNearest(currentFramework);
if (dependencySet != null)
{
var set = dependencySet.Packages;
if (set != null)
{
lockFileLib.Dependencies = set.AsList();
}
}
}
else
{
// Filter the dependency set down to packages and projects.
// Framework references will not be displayed
lockFileLib.Dependencies = dependencies
.Where(ld => ld.LibraryRange.TypeConstraintAllowsAnyOf(LibraryDependencyTarget.PackageProjectExternal))
.Select(ld => new PackageDependency(ld.Name, ld.LibraryRange.VersionRange))
.ToList();
}
}
/// <summary>
/// Create a library for a project.
/// </summary>
public static LockFileTargetLibrary CreateLockFileTargetProject(
GraphItem<RemoteResolveResult> graphItem,
LibraryIdentity library,
LibraryIncludeFlags dependencyType,
RestoreTargetGraph targetGraph,
ProjectStyle rootProjectStyle)
{
var localMatch = (LocalMatch)graphItem.Data.Match;
// Target framework information is optional and may not exist for csproj projects
// that do not have a project.json file.
string projectFramework = null;
object frameworkInfoObject;
if (localMatch.LocalLibrary.Items.TryGetValue(
KnownLibraryProperties.TargetFrameworkInformation,
out frameworkInfoObject))
{
// Retrieve the resolved framework name, if this is null it means that the
// project is incompatible. This is marked as Unsupported.
var targetFrameworkInformation = (TargetFrameworkInformation)frameworkInfoObject;
projectFramework = targetFrameworkInformation.FrameworkName?.DotNetFrameworkName
?? NuGetFramework.UnsupportedFramework.DotNetFrameworkName;
}
// Create the target entry
var projectLib = new LockFileTargetLibrary()
{
Name = library.Name,
Version = library.Version,
Type = LibraryType.Project,
Framework = projectFramework,
// Find all dependencies which would be in the nuspec
// Include dependencies with no constraints, or package/project/external
// Exclude suppressed dependencies, the top level project is not written
// as a target so the node depth does not matter.
Dependencies = graphItem.Data.Dependencies
.Where(
d => (d.LibraryRange.TypeConstraintAllowsAnyOf(LibraryDependencyTarget.PackageProjectExternal))
&& d.SuppressParent != LibraryIncludeFlags.All
&& d.ReferenceType == LibraryDependencyReferenceType.Direct)
.Select(d => GetDependencyVersionRange(d))
.ToList()
};
if (rootProjectStyle == ProjectStyle.PackageReference)
{
if (localMatch.LocalLibrary.Items.TryGetValue(KnownLibraryProperties.MSBuildProjectPath, out object msbuildPath))
{
// Find the project path, this is provided by the resolver
var msbuildFilePathInfo = new FileInfo((string)msbuildPath);
// Ensure a trailing slash for the relative path helper.
var projectDir = PathUtility.EnsureTrailingSlash(msbuildFilePathInfo.Directory.FullName);
// Create an ordered list of selection criteria. Each will be applied, if the result is empty
// fallback frameworks from "imports" will be tried.
// These are only used for framework/RID combinations where content model handles everything.
var orderedCriteria = CreateCriteria(targetGraph.Conventions, targetGraph.Framework, targetGraph.RuntimeIdentifier);
string libAnyPath = $"lib/{targetGraph.Framework.GetShortFolderName()}/any.dll";
var contentItems = new ContentItemCollection();
if (localMatch.LocalLibrary.Items.TryGetValue(KnownLibraryProperties.ProjectRestoreMetadataFiles, out object filesObject))
{
List<ProjectRestoreMetadataFile> files = (List<ProjectRestoreMetadataFile>)filesObject;
if (files.Count > 0)
{
var fileLookup = new Dictionary<string, ProjectRestoreMetadataFile>(StringComparer.OrdinalIgnoreCase);
// Process and de-dupe files
for (var i = 0; i < files.Count; i++)
{
var path = files[i].PackagePath;
// LIBANY avoid compatibility checks and will always be used.
if (LIBANY.Equals(path, StringComparison.Ordinal))
{
path = libAnyPath;
}
if (!fileLookup.ContainsKey(path))
{
fileLookup.Add(path, files[i]);
}
}
contentItems.Load(fileLookup.Keys);
// Compile
// ref takes precedence over lib
var compileGroup = GetLockFileItems(
orderedCriteria,
contentItems,
targetGraph.Conventions.Patterns.CompileRefAssemblies,
targetGraph.Conventions.Patterns.CompileLibAssemblies);
projectLib.CompileTimeAssemblies = ConvertToProjectPaths(fileLookup, projectDir, compileGroup);
// Runtime
var runtimeGroup = GetLockFileItems(
orderedCriteria,
contentItems,
targetGraph.Conventions.Patterns.RuntimeAssemblies);
projectLib.RuntimeAssemblies = ConvertToProjectPaths(fileLookup, projectDir, runtimeGroup);
}
else
{
// If the project did not provide a list of assets, add in default ones.
contentItems.Load([libAnyPath]);
// When there's only lib assets, compile and runtime groups are always equivalent.
var compileGroup = GetLockFileItems(
orderedCriteria,
contentItems,
targetGraph.Conventions.Patterns.CompileLibAssemblies);
if (compileGroup.Count > 0)
{
string relativePath = PathUtility.GetPathWithForwardSlashes(Path.Combine("bin", "placeholder", $"{localMatch.Library.Name}.dll"));
var lockFileItem = new LockFileItem(relativePath);
projectLib.CompileTimeAssemblies = new List<LockFileItem>() { lockFileItem };
projectLib.RuntimeAssemblies = new List<LockFileItem>() { lockFileItem };
}
}
}
}
}
// Add frameworkAssemblies for projects
object frameworkAssembliesObject;
if (localMatch.LocalLibrary.Items.TryGetValue(
KnownLibraryProperties.FrameworkAssemblies,
out frameworkAssembliesObject))
{
projectLib.FrameworkAssemblies.AddRange((List<string>)frameworkAssembliesObject);
}
// Add frameworkReferences for projects
object frameworkReferencesObject;
if (localMatch.LocalLibrary.Items.TryGetValue(
KnownLibraryProperties.FrameworkReferences,
out frameworkReferencesObject))
{
projectLib.FrameworkReferences.AddRange(
((IReadOnlyCollection<FrameworkDependency>)frameworkReferencesObject)
.Where(e => e.PrivateAssets != FrameworkDependencyFlags.All)
.Select(f => f.Name));
}
// Exclude items
ExcludeItems(projectLib, dependencyType);
projectLib.Freeze();
return projectLib;
}
/// <summary>
/// Convert from the expected nupkg path to the on disk path.
/// </summary>
private static List<LockFileItem> ConvertToProjectPaths(
Dictionary<string, ProjectRestoreMetadataFile> fileLookup,
string projectDir,
IList<LockFileItem> items)
{
var results = new List<LockFileItem>(items.Count);
foreach (var item in items.NoAllocEnumerate())
{
var diskPath = fileLookup[item.Path].AbsolutePath;
var fixedPath = PathUtility.GetPathWithForwardSlashes(
PathUtility.GetRelativePath(projectDir, diskPath));
results.Add(new LockFileItem(fixedPath));
}
return results;
}
/// <summary>
/// Create lock file items for the best matching group, and optionally output the selected framework.
/// </summary>
/// <remarks>Enumerate this once after calling.</remarks>
private static IList<LockFileItem> GetLockFileItems(
List<SelectionCriteria> criteria,
ContentItemCollection items,
Action<LockFileItem> additionalAction,
out NuGetFramework selectedFramework,
params PatternSet[] patterns)
{
selectedFramework = null;
List<LockFileItem> result = null;
// Loop through each criteria taking the first one that matches one or more items.
foreach (var managedCriteria in criteria)
{
var group = items.FindBestItemGroup(
managedCriteria,
patterns);
if (group != null)
{
if (group.Properties.TryGetValue(
ManagedCodeConventions.PropertyNames.TargetFrameworkMoniker, out object tfmObj))
{
selectedFramework = tfmObj as NuGetFramework;
}
result = new(group.Items.Count);
foreach (var item in group.Items.NoAllocEnumerate())
{
var newItem = new LockFileItem(item.Path);
object locale;
if (item.Properties.TryGetValue(ManagedCodeConventions.PropertyNames.Locale, out locale))
{
newItem.Properties[ManagedCodeConventions.PropertyNames.Locale] = (string)locale;
}
object related;
if (item.Properties.TryGetValue("related", out related))
{
newItem.Properties["related"] = (string)related;
}
additionalAction?.Invoke(newItem);
result.Add(newItem);
}
// Take only the first group that has items
break;
}
}
return result ?? new();
}
/// <summary>
/// Create lock file items for the best matching group.
/// </summary>
/// <remarks>Enumerate this once after calling.</remarks>
private static IList<LockFileItem> GetLockFileItems(
List<SelectionCriteria> criteria,
ContentItemCollection items,
params PatternSet[] patterns)
{
return GetLockFileItems(criteria, items, additionalAction: null, out _, patterns);
}
/// <summary>
/// Get packageId.targets and packageId.props
/// </summary>
private static IEnumerable<LockFileItem> GetBuildItemsForPackageId(
IList<LockFileItem> items,
string packageId)
{
if (items.Count > 0)
{
var skipEmptyCheck = false;
var ordered = items.OrderBy(c => c.Path, StringComparer.OrdinalIgnoreCase)
.ToArray();
var props = ordered.FirstOrDefault(c =>
$"{packageId}.props".Equals(
Path.GetFileName(c.Path),
StringComparison.OrdinalIgnoreCase));
if (props != null)
{
skipEmptyCheck = true;
yield return props;
}
var targets = ordered.FirstOrDefault(c =>
$"{packageId}.targets".Equals(
Path.GetFileName(c.Path),
StringComparison.OrdinalIgnoreCase));
if (targets != null)
{
skipEmptyCheck = true;
yield return targets;
}
if (!skipEmptyCheck)
{
// Find _._ if it exists, this file is needed
// but does not match the package id above.
var empty = ordered.FirstOrDefault(c =>
c.Path.EndsWith(PackagingCoreConstants.ForwardSlashEmptyFolder, StringComparison.Ordinal));
if (empty != null)
{
yield return empty;
}
}
}
}
/// <summary>
/// Creates an ordered list of selection criteria to use. This supports fallback frameworks.
/// </summary>
private static List<SelectionCriteria> CreateCriteria(
ManagedCodeConventions conventions,
NuGetFramework framework,
string runtimeIdentifier)
{
List<SelectionCriteria> managedCriteria;
var fallbackFramework = framework as FallbackFramework;
// Avoid fallback criteria if this is not a fallback framework,
// or if AssetTargetFallback is used. For AssetTargetFallback
// the fallback frameworks will be checked later.
if (fallbackFramework == null)
{
var standardCriteria = conventions.Criteria.ForFrameworkAndRuntime(
framework,
runtimeIdentifier);
managedCriteria = new(capacity: 1)
{
standardCriteria
};
}
else
{
// Add the project framework
var primaryFramework = NuGetFramework.Parse(fallbackFramework.DotNetFrameworkName);
var primaryCriteria = conventions.Criteria.ForFrameworkAndRuntime(
primaryFramework,
runtimeIdentifier);
managedCriteria = new(capacity: 1 + fallbackFramework.Fallback.Count)
{
primaryCriteria
};
// Add each fallback framework in order
foreach (var fallback in fallbackFramework.Fallback)
{
var fallbackCriteria = conventions.Criteria.ForFrameworkAndRuntime(
fallback,
runtimeIdentifier);
managedCriteria.Add(fallbackCriteria);
}
}
return managedCriteria;
}
/// <summary>
/// Clears a lock file group and replaces the first item with _._ if
/// the group has items. Empty groups are left alone.
/// </summary>
private static void ClearIfExists<T>(IList<T> group, Func<string, T> factory) where T : LockFileItem
{
if (GroupHasNonEmptyItems(group))
{
// Take the root directory
var firstItem = group.OrderBy(item => item.Path.LastIndexOf('/'))
.ThenBy(item => item.Path, StringComparer.OrdinalIgnoreCase)
.First();
var fileName = Path.GetFileName(firstItem.Path);
Debug.Assert(!string.IsNullOrEmpty(fileName));
#if NETCOREAPP
Debug.Assert(firstItem.Path.IndexOf('/', StringComparison.Ordinal) > 0);
#else
Debug.Assert(firstItem.Path.IndexOf('/') > 0);
#endif
var emptyDir = firstItem.Path.Substring(0, firstItem.Path.Length - fileName.Length)
+ PackagingCoreConstants.EmptyFolder;
group.Clear();
// Create a new item with the _._ path
var emptyItem = factory(emptyDir);
// Copy over the properties from the first
foreach (var pair in firstItem.Properties)
{
emptyItem.Properties.Add(pair.Key, pair.Value);
}
group.Add(emptyItem);
}
}
/// <summary>
/// True if the group has items that do not end with _._
/// </summary>
private static bool GroupHasNonEmptyItems(IEnumerable<LockFileItem> group)
{
return group?.Any(item => !item.Path.EndsWith(PackagingCoreConstants.ForwardSlashEmptyFolder, StringComparison.Ordinal)) == true;
}
/// <summary>
/// Group all items by the primary key, then select the nearest TxM
/// within each group.
/// Items that do not contain the primaryKey will be filtered out.
/// </summary>
private static List<ContentItemGroup> GetContentGroupsForFramework(
NuGetFramework framework,
List<ContentItemGroup> contentGroups,
string primaryKey)
{
var groups = new List<ContentItemGroup>();
// Group by primary key and find the nearest TxM under each.
var primaryGroups = new Dictionary<string, List<ContentItemGroup>>(StringComparer.Ordinal);
foreach (var group in contentGroups)
{
object keyObj;
if (group.Properties.TryGetValue(primaryKey, out keyObj))
{
var key = (string)keyObj;
List<ContentItemGroup> index;
if (!primaryGroups.TryGetValue(key, out index))
{
index = new List<ContentItemGroup>(1);
primaryGroups.Add(key, index);
}
index.Add(group);
}
}
// Find the nearest TxM within each primary key group.
foreach (var primaryGroup in primaryGroups)
{
var groupedItems = primaryGroup.Value;
var nearestGroup = NuGetFrameworkUtility.GetNearest<ContentItemGroup>(groupedItems, framework,
group =>
{
// In the case of /native there is no TxM, here any should be used.
object frameworkObj;
if (group.Properties.TryGetValue(
ManagedCodeConventions.PropertyNames.TargetFrameworkMoniker,
out frameworkObj))
{
return (NuGetFramework)frameworkObj;
}
return NuGetFramework.AnyFramework;
});
// If a compatible group exists within the secondary key add it to the results
if (nearestGroup != null)
{
groups.Add(nearestGroup);
}
}
return groups;
}
private static List<LockFileRuntimeTarget> GetRuntimeTargetLockFileItems(
ContentItemCollection contentItems,
NuGetFramework framework,
LibraryIncludeFlags dependencyType,
LibraryIncludeFlags groupType,
PatternSet patternSet,
string assetType)
{
List<ContentItemGroup> groups = new List<ContentItemGroup>();
contentItems.PopulateItemGroups(patternSet, groups);
var groupsForFramework = GetContentGroupsForFramework(
framework,
groups,
ManagedCodeConventions.PropertyNames.RuntimeIdentifier);
var items = GetRuntimeTargetItems(groupsForFramework, assetType);
if ((dependencyType & groupType) == LibraryIncludeFlags.None)
{
ClearIfExists(items, static path => new LockFileRuntimeTarget(path));
}
return items;
}
/// <summary>
/// Create LockFileItems from groups of library items.
/// </summary>
/// <param name="groups">Library items grouped by RID.</param>
/// <param name="assetType">Lock file section the items apply to.</param>
private static List<LockFileRuntimeTarget> GetRuntimeTargetItems(List<ContentItemGroup> groups, string assetType)
{
var results = new List<LockFileRuntimeTarget>();
// Loop through RID groups
foreach (var group in groups)
{
var rid = (string)group.Properties[ManagedCodeConventions.PropertyNames.RuntimeIdentifier];
// Create lock file entries for each assembly.
foreach (var item in group.Items.NoAllocEnumerate())
{
results.Add(new LockFileRuntimeTarget(item.Path)
{
AssetType = assetType,
Runtime = rid
});
}
}
return results;
}
/// <summary>
/// Replace / with the local directory separator if needed.