-
Notifications
You must be signed in to change notification settings - Fork 696
/
Copy pathDependencyGraphResolver.cs
1394 lines (1169 loc) · 81.4 KB
/
DependencyGraphResolver.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. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Common;
using NuGet.DependencyResolver;
using NuGet.Frameworks;
using NuGet.LibraryModel;
using NuGet.Packaging;
using NuGet.ProjectModel;
using NuGet.Repositories;
using NuGet.RuntimeModel;
using NuGet.Versioning;
namespace NuGet.Commands
{
/// <summary>
/// Represents a class that can resolve a dependency graph.
/// </summary>
internal sealed partial class DependencyGraphResolver
{
/// <summary>
/// Defines the default size for the queue used to process dependency graph items.
/// </summary>
private const int DependencyGraphItemQueueSize = 4096;
/// <summary>
/// Defines the default size for the evictions queue used to process evictions.
/// </summary>
private const int EvictionsDictionarySize = 1024;
/// <summary>
/// Defines the default size for the dictionary that stores the resolved dependency graph items.
/// </summary>
private const int ResolvedDependencyGraphItemDictionarySize = 2048;
/// <summary>
/// A <see cref="DependencyGraphItemIndexer" /> used to index dependency graph items.
/// </summary>
private readonly DependencyGraphItemIndexer _indexingTable = new();
/// <summary>
/// A <see cref="RestoreCollectorLogger" /> used for logging.
/// </summary>
private readonly RestoreCollectorLogger _logger;
/// <summary>
/// The <see cref="RestoreRequest" /> of the current restore that provides information about the project's configuration.
/// </summary>
private readonly RestoreRequest _request;
/// <summary>
/// Represents the path for any dependency that is directly referenced by the root project.
/// </summary>
private readonly LibraryRangeIndex[] _rootedDependencyPath = new[] { LibraryRangeIndex.Project };
/// <summary>
/// A <see cref="TelemetryActivity" /> instance used for telemetry.
/// </summary>
private readonly TelemetryActivity _telemetryActivity;
/// <summary>
/// Initializes a new instance of the <see cref="DependencyGraphResolver" /> class.
/// </summary>
/// <param name="logger">A <see cref="RestoreCollectorLogger" /> to use for logging.</param>
/// <param name="restoreRequest">The <see cref="RestoreRequest" /> for the restore.</param>
/// <param name="telemetryActivity">A <see cref="TelemetryActivity" /> instance to use for logging telemetry.</param>
public DependencyGraphResolver(RestoreCollectorLogger logger, RestoreRequest restoreRequest, TelemetryActivity telemetryActivity)
{
_logger = logger;
_request = restoreRequest;
_telemetryActivity = telemetryActivity;
}
/// <summary>
/// Resolves the dependency graph for the project for all of its configured target frameworks and runtime identifiers.
/// </summary>
/// <param name="userPackageFolder">A <see cref="NuGetv3LocalRepository" /> representing the global packages folder configured for restore.</param>
/// <param name="fallbackPackageFolders">A <see cref="IReadOnlyList{T}" /> of <see cref="NuGetv3LocalRepository" /> objects that represent the package fallback folders configured for restore.</param>
/// <param name="context">The <see cref="RemoteWalkContext" /> to use for this restore.</param>
/// <param name="projectRestoreCommand">A <see cref="ProjectRestoreCommand" /> instance to use for installing packages.</param>
/// <param name="localRepositories">A <see cref="List{T}" /> of <see cref="NuGetv3LocalRepository" /> objects that represent the local package repositories configured for restore.</param>
/// <param name="token">A <see cref="CancellationToken" /> to use for cancellation.</param>
/// <returns>A <see cref="ValueTuple{T1, T2, T3}" /> with:<br />
/// <list type="bullet">
/// <item>A <see langword="bool" /> representing the overall success of the dependency graph resolution.</item>
/// <item>A <see cref="List{T}" /> of <see cref="RestoreTargetGraph" /> objects representing the resolved dependency graphs for each pair of target framework and runtime identifier.</item>
/// <item>A <see cref="RuntimeGraph" /> representing the runtime graph of the resolved dependency graph.</item>
/// </list>
/// </returns>
public async Task<ValueTuple<bool, List<RestoreTargetGraph>, RuntimeGraph>> ResolveAsync(
NuGetv3LocalRepository userPackageFolder,
IReadOnlyList<NuGetv3LocalRepository> fallbackPackageFolders,
RemoteWalkContext context,
ProjectRestoreCommand projectRestoreCommand,
List<NuGetv3LocalRepository> localRepositories,
CancellationToken token)
{
_telemetryActivity.StartIntervalMeasure();
// Keeps track of the overall success of the dependency graph resolution
bool success = true;
// Calculate whether or not transitive pinning is enabled
bool isCentralPackageTransitivePinningEnabled = _request.Project.RestoreMetadata != null && _request.Project.RestoreMetadata.CentralPackageVersionsEnabled & _request.Project.RestoreMetadata.CentralPackageTransitivePinningEnabled;
// Keeps track of all of the packages that were installed
HashSet<LibraryIdentity> installedPackages = new();
// Stores the list of all graphs
List<RestoreTargetGraph> allGraphs = new();
// Stores the list of graphs without a runtime identifier by their target framework
Dictionary<NuGetFramework, RestoreTargetGraph> graphsByTargetFramework = new();
// Stores the list graphs that are runtime identifier specific
List<RestoreTargetGraph> runtimeGraphs = new();
// Keeps track of all runtime graphs that exist in the dependency graph
RuntimeGraph allRuntimes = RuntimeGraph.Empty;
// Keeps track of whether or not we've installed all of the RID-less packages since they contain a runtime.json and are needed before the RID-specific graphs can be resolved
bool hasInstallBeenCalledAlready = false;
// Stores the list of download results which contribute to the overall success of the graph resolution
DownloadDependencyResolutionResult[]? downloadDependencyResolutionResults = default;
// A LibraryDependency representing the root of the graph which is the project itself
LibraryDependency mainProjectDependency = new(
new LibraryRange()
{
Name = _request.Project.Name,
VersionRange = new VersionRange(_request.Project.Version),
TypeConstraint = LibraryDependencyTarget.Project | LibraryDependencyTarget.ExternalProject
});
// Create the list of framework/runtime pairs to resolve graphs for. This method returns the pairs in order with the target framework pairs without runtime identifiers come first
List<FrameworkRuntimePair> projectFrameworkRuntimePairs = RestoreCommand.CreateFrameworkRuntimePairs(_request.Project, runtimeIds: RequestRuntimeUtility.GetRestoreRuntimes(_request));
// Loop through the target framework and runtime identifier pairs to resolve each graph.
// The pairs are sorted with all of the RID-less framework pairs first
foreach (FrameworkRuntimePair frameworkRuntimePair in projectFrameworkRuntimePairs.NoAllocEnumerate())
{
// Since the FrameworkRuntimePair objects are sorted, the packages found so far need to be installed before resolving any runtime identifier specific graphs because
// the runtime.json is in the package which is used to determine what runtime packages to add
if (!string.IsNullOrWhiteSpace(frameworkRuntimePair.RuntimeIdentifier) && !hasInstallBeenCalledAlready)
{
downloadDependencyResolutionResults = await ProjectRestoreCommand.DownloadDependenciesAsync(_request.Project, context, _telemetryActivity, telemetryPrefix: string.Empty, token);
success &= await projectRestoreCommand.InstallPackagesAsync(installedPackages, allGraphs, downloadDependencyResolutionResults, userPackageFolder, token);
// This ensures that the packages for the RID-less graph are only installed once
hasInstallBeenCalledAlready = true;
}
// Get the corresponding TargetFrameworkInformation from the restore request
TargetFrameworkInformation projectTargetFramework = _request.Project.GetTargetFramework(frameworkRuntimePair.Framework)!;
// Keeps track of the unresolved packages
HashSet<LibraryRange> unresolvedPackages = new();
// Keeps track of the resolved packages
HashSet<ResolvedDependencyKey> resolvedPackages = new();
if (TryGetRuntimeGraph(localRepositories, graphsByTargetFramework, frameworkRuntimePair, projectTargetFramework, out RuntimeGraph? runtimeGraph))
{
// Merge all of the runtime graphs together
allRuntimes = RuntimeGraph.Merge(allRuntimes, runtimeGraph);
}
// Stores a dictionary of central package versions by their LibraryDependencyIndex for faster lookup when using CPM
Dictionary<LibraryDependencyIndex, VersionRange>? pinnedPackageVersions = IndexPinnedPackageVersions(isCentralPackageTransitivePinningEnabled, projectTargetFramework);
// Create a DependencyGraphItem representing the root project to add to the queue for processing
DependencyGraphItem rootProjectDependencyGraphItem = new()
{
LibraryDependency = mainProjectDependency,
LibraryDependencyIndex = LibraryDependencyIndex.Project,
LibraryRangeIndex = LibraryRangeIndex.Project,
Suppressions = new HashSet<LibraryDependencyIndex>(),
FindLibraryTask = ResolverUtility.FindLibraryCachedAsync(
mainProjectDependency.LibraryRange,
frameworkRuntimePair.Framework,
runtimeIdentifier: string.IsNullOrWhiteSpace(frameworkRuntimePair.RuntimeIdentifier) ? null : frameworkRuntimePair.RuntimeIdentifier,
context,
token),
Parent = LibraryRangeIndex.None
};
// Resolve the entire dependency graph
Dictionary<LibraryDependencyIndex, ResolvedDependencyGraphItem> resolvedDependencyGraphItems = await ResolveDependencyGraphItemsAsync(
isCentralPackageTransitivePinningEnabled,
frameworkRuntimePair,
projectTargetFramework,
runtimeGraph,
pinnedPackageVersions,
rootProjectDependencyGraphItem,
context,
token);
// Now that the graph has been resolved, we need to create walk all of the defined dependencies again to detect any cycles and downgrades. The RestoreTargetGraph stores all of the
// information about the graph including the nodes with their parent/child relationships, cycles, downgrades, and conflicts.
(bool wasRestoreTargetGraphCreationSuccessful, RestoreTargetGraph restoreTargetGraph) = await CreateRestoreTargetGraphAsync(frameworkRuntimePair, runtimeGraph, isCentralPackageTransitivePinningEnabled, unresolvedPackages, resolvedPackages, resolvedDependencyGraphItems, context);
success &= wasRestoreTargetGraphCreationSuccessful;
// Track all of the RestoreTargetGraph objects
allGraphs.Add(restoreTargetGraph);
if (!string.IsNullOrWhiteSpace(frameworkRuntimePair.RuntimeIdentifier))
{
// Track all of the runtime specific graphs
runtimeGraphs.Add(restoreTargetGraph);
}
else
{
// Track all of the RID-less graphs by their target framework
graphsByTargetFramework.Add(frameworkRuntimePair.Framework, restoreTargetGraph);
}
}
_telemetryActivity.EndIntervalMeasure(ProjectRestoreCommand.WalkFrameworkDependencyDuration);
// Install packages if they weren't already. If the graph has not runtimes, installing of packages won't be called until this point
if (!hasInstallBeenCalledAlready)
{
downloadDependencyResolutionResults = await ProjectRestoreCommand.DownloadDependenciesAsync(_request.Project, context, _telemetryActivity, telemetryPrefix: string.Empty, token);
success &= await projectRestoreCommand.InstallPackagesAsync(installedPackages, allGraphs, downloadDependencyResolutionResults, userPackageFolder, token);
hasInstallBeenCalledAlready = true;
}
// Install runtime specific packages if applicable
if (runtimeGraphs.Count > 0)
{
success &= await projectRestoreCommand.InstallPackagesAsync(installedPackages, runtimeGraphs, Array.Empty<DownloadDependencyResolutionResult>(), userPackageFolder, token);
}
foreach (KeyValuePair<string, CompatibilityProfile> profile in _request.Project.RuntimeGraph.Supports)
{
CompatibilityProfile? compatProfile;
if (profile.Value.RestoreContexts.Any())
{
// Just use the contexts from the project definition
compatProfile = profile.Value;
}
else if (!allRuntimes.Supports.TryGetValue(profile.Value.Name, out compatProfile))
{
// No definition of this profile found, so just continue to the next one
await _logger.LogAsync(RestoreLogMessage.CreateWarning(NuGetLogCode.NU1502, string.Format(CultureInfo.CurrentCulture, Strings.Log_UnknownCompatibilityProfile, profile.Key)));
continue;
}
foreach (FrameworkRuntimePair? frameworkRuntimePair in compatProfile.RestoreContexts)
{
_logger.LogDebug($" {profile.Value.Name} -> +{frameworkRuntimePair}");
_request.CompatibilityProfiles.Add(frameworkRuntimePair);
}
}
// Log the final results like downgrades, conflicts, and cycles
_logger.ApplyRestoreOutput(allGraphs);
// Log information for unexpected dependencies
await UnexpectedDependencyMessages.LogAsync(allGraphs, _request.Project, _logger);
// Determine if the graph resolution was successful (no conflicts or unresolved packages)
success &= await projectRestoreCommand.ResolutionSucceeded(allGraphs, downloadDependencyResolutionResults, context, token);
return (success, allGraphs, allRuntimes);
}
/// <summary>
/// Creates a <see cref="RestoreTargetGraph" /> from the resolved dependency graph items and analyzes the graph for cycles, downgrades, and conflicts.
/// </summary>
/// <param name="frameworkRuntimePair">The <see cref="FrameworkRuntimePair" /> of the dependency graph.</param>
/// <param name="runtimeGraph">The <see cref="RuntimeGraph" /> of the dependency graph.</param>
/// <param name="isCentralPackageTransitivePinningEnabled">A <see cref="bool" /> indicating whether or not central transitive pinning is enabled.</param>
/// <param name="unresolvedPackages">A <see cref="HashSet{T}" /> containing <see cref="LibraryRange" /> objects representing packages that could not be resolved.</param>
/// <param name="resolvedPackages">A <see cref="HashSet{T}" /> containing <see cref="ResolvedDependencyKey" /> objects representing packages that were successfully resolved.</param>
/// <param name="context">The <see cref="RemoteWalkContext" /> for the restore.</param>
/// <returns>A <see cref="ValueTuple{T1, T2}" /> with:<br />
/// <list type="bullet">
/// <item>A <see langword="bool" /> indicating if the dependency graph contains no issues.</item>
/// <item>A <see cref="RestoreTargetGraph" /> representing the fully resolved and analyzed dependency graph.</item>
/// </list>
/// </returns>
private static async Task<(bool Success, RestoreTargetGraph RestoreTargetGraph)> CreateRestoreTargetGraphAsync(
FrameworkRuntimePair frameworkRuntimePair,
RuntimeGraph? runtimeGraph,
bool isCentralPackageTransitivePinningEnabled,
HashSet<LibraryRange> unresolvedPackages,
HashSet<ResolvedDependencyKey> resolvedPackages,
Dictionary<LibraryDependencyIndex, ResolvedDependencyGraphItem> resolvedDependencyGraphItems,
RemoteWalkContext context)
{
bool success = true;
// Stores results of analyzing the graph including conflicts, cycles, and downgrades
AnalyzeResult<RemoteResolveResult> analyzeResult = new();
// Stores the list of items in as a flat list
HashSet<GraphItem<RemoteResolveResult>> flattenedGraphItems = new();
// Stores the list of graph nodes which point to their outer and inner nodes which represent the graph as a tree
List<GraphNode<RemoteResolveResult>> graphNodes = new();
// Stores the list of nodes by their LibraryRangeIndex for faster lookup
Dictionary<LibraryRangeIndex, GraphNode<RemoteResolveResult>> nodesById = new();
// Keeps track of visited items to detect when we come across a dependency that was already visited. Any time a dependency is seen again, we need to determine if there was a downgrade or conflict.
HashSet<LibraryDependencyIndex> visitedItems = new();
// Stores the items to process, starting with the project itself and its children
Queue<(LibraryDependencyIndex, LibraryRangeIndex, GraphNode<RemoteResolveResult>)> itemsToFlatten = new();
Dictionary<LibraryRangeIndex, GraphNode<RemoteResolveResult>> versionConflicts = new();
// Stores the list of downgrades
Dictionary<LibraryRangeIndex, (LibraryRangeIndex FromParentLibraryRangeIndex, LibraryDependency FromLibraryDependency, LibraryRangeIndex ToParentLibraryRangeIndex, LibraryDependencyIndex ToLibraryDependencyIndex, bool IsCentralTransitive)> downgrades = new();
// Get the resolved item for the project
ResolvedDependencyGraphItem projectResolvedDependencyGraphItem = resolvedDependencyGraphItems[LibraryDependencyIndex.Project];
// Create a node representing the root for the project
GraphNode<RemoteResolveResult> rootGraphNode = new GraphNode<RemoteResolveResult>(projectResolvedDependencyGraphItem.LibraryDependency.LibraryRange)
{
Item = projectResolvedDependencyGraphItem.Item
};
graphNodes.Add(rootGraphNode);
// Enqueue the project to be processed
itemsToFlatten.Enqueue((LibraryDependencyIndex.Project, projectResolvedDependencyGraphItem.LibraryRangeIndex, rootGraphNode));
nodesById.Add(projectResolvedDependencyGraphItem.LibraryRangeIndex, rootGraphNode);
while (itemsToFlatten.Count > 0)
{
(LibraryDependencyIndex currentLibraryDependencyIndex, LibraryRangeIndex currentLibraryRangeIndex, GraphNode<RemoteResolveResult> currentGraphNode) = itemsToFlatten.Dequeue();
// If there was no dependency in the resolved graph with the same name, it can be skipped and left out of the final graph
if (!resolvedDependencyGraphItems.TryGetValue(currentLibraryDependencyIndex, out ResolvedDependencyGraphItem? resolvedDependencyGraphItem))
{
continue;
}
flattenedGraphItems.Add(resolvedDependencyGraphItem.Item);
for (int i = 0; i < resolvedDependencyGraphItem.Item.Data.Dependencies.Count; i++)
{
LibraryDependency childLibraryDependency = resolvedDependencyGraphItem.Item.Data.Dependencies[i];
if (childLibraryDependency.LibraryRange.VersionRange == null)
{
continue;
}
if (StringComparer.OrdinalIgnoreCase.Equals(childLibraryDependency.Name, resolvedDependencyGraphItem.Item.Key.Name) || StringComparer.OrdinalIgnoreCase.Equals(childLibraryDependency.Name, rootGraphNode.Key.Name))
{
// A cycle exists since the current child dependency has the same name as its parent or as the root node
GraphNode<RemoteResolveResult> nodeWithCycle = new(childLibraryDependency.LibraryRange)
{
OuterNode = currentGraphNode,
Disposition = Disposition.Cycle
};
analyzeResult.Cycles.Add(nodeWithCycle);
continue;
}
LibraryDependencyIndex childLibraryDependencyIndex = resolvedDependencyGraphItem.GetDependencyIndexForDependencyAt(i);
if (!resolvedDependencyGraphItems.TryGetValue(childLibraryDependencyIndex, out ResolvedDependencyGraphItem? childResolvedDependencyGraphItem))
{
// If there was no dependency in the resolved graph with the same name as this child dependency, it can be skipped and left out of the final graph
continue;
}
LibraryRangeIndex childResolvedLibraryRangeIndex = childResolvedDependencyGraphItem.LibraryRangeIndex;
LibraryDependency childResolvedLibraryDependency = childResolvedDependencyGraphItem.LibraryDependency;
// Determine if this dependency has already been visited
if (!visitedItems.Add(childLibraryDependencyIndex))
{
LibraryRangeIndex currentRangeIndex = resolvedDependencyGraphItem.GetRangeIndexForDependencyAt(i);
if (resolvedDependencyGraphItem.Path.Contains(currentRangeIndex))
{
// If the dependency exists in the its own path, then a cycle exists
analyzeResult.Cycles.Add(
new GraphNode<RemoteResolveResult>(childLibraryDependency.LibraryRange)
{
OuterNode = currentGraphNode,
Disposition = Disposition.Cycle
});
continue;
}
// Verify downgrades only if the resolved dependency has a lower version than what was defined
if (!RemoteDependencyWalker.IsGreaterThanOrEqualTo(childResolvedLibraryDependency.LibraryRange.VersionRange, childLibraryDependency.LibraryRange.VersionRange))
{
// It is not a downgrade if: the dependency is transitive and is suppressed its parent or any of those parents' parent because the suppressions is an aggregate of everything suppressed above.
// For example, A -> B (PrivateAssets=All) -> C
// When processing C, it is not suppressed but its parent is, which is tracked in ResolvedDependencyGraphItem.Suppressions
if ((childLibraryDependencyIndex != LibraryDependencyIndex.Project && childLibraryDependency.SuppressParent == LibraryIncludeFlags.All)
|| resolvedDependencyGraphItem.Suppressions.Count > 0 && resolvedDependencyGraphItem.Suppressions[0].Contains(childLibraryDependencyIndex))
{
continue;
}
// Get the resolved version in case a floating version like 1.* was specified
NuGetVersion? resolvedVersion = childResolvedDependencyGraphItem.Item.Data.Match?.Library?.Version;
if (resolvedVersion != null && childLibraryDependency.LibraryRange.VersionRange.Satisfies(resolvedVersion))
{
// Ignore the lower version if the resolved version satisfies the range of the dependency. This can happen when a floating version like 1.* was specified
// and the resolved version is 1.2.3, which satisfies the range of 1.*
continue;
}
// This lower version could be a downgrade if it hasn't already been seen
if (!downgrades.ContainsKey(childResolvedLibraryRangeIndex))
{
// Determine if any parents have actually eclipsed this version
if (childResolvedDependencyGraphItem.ParentPathsThatHaveBeenEclipsed != null)
{
bool hasBeenEclipsedByParent = false;
foreach (LibraryRangeIndex parent in childResolvedDependencyGraphItem.ParentPathsThatHaveBeenEclipsed)
{
if (resolvedDependencyGraphItem.Path.Contains(parent))
{
hasBeenEclipsedByParent = true;
break;
}
}
if (hasBeenEclipsedByParent)
{
continue;
}
}
// Look through all of the parent nodes to see if any are a downgrade
bool foundParentDowngrade = false;
if (childResolvedDependencyGraphItem.Parents != null)
{
foreach (LibraryRangeIndex parentLibraryRangeIndex in childResolvedDependencyGraphItem.Parents)
{
if (resolvedDependencyGraphItem.Path.Contains(parentLibraryRangeIndex) && !resolvedDependencyGraphItem.IsRootPackageReference)
{
downgrades.Add(
childResolvedLibraryRangeIndex,
(
FromParentLibraryRangeIndex: resolvedDependencyGraphItem.LibraryRangeIndex,
FromLibraryDependency: childLibraryDependency,
ToParentLibraryRangeIndex: parentLibraryRangeIndex,
ToLibraryDependencyIndex: childLibraryDependencyIndex,
IsCentralTransitive: isCentralPackageTransitivePinningEnabled ? childResolvedDependencyGraphItem.IsCentrallyPinnedTransitivePackage : false
));
foundParentDowngrade = true;
break;
}
}
}
// It is a downgrade if central transitive pinning is not being used or if the child is not a direct package reference
if (!foundParentDowngrade && (!isCentralPackageTransitivePinningEnabled || !childResolvedDependencyGraphItem.IsRootPackageReference))
{
downgrades.Add(
childResolvedLibraryRangeIndex,
(
FromParentLibraryRangeIndex: resolvedDependencyGraphItem.LibraryRangeIndex,
FromLibraryDependency: childLibraryDependency,
ToParentLibraryRangeIndex: childResolvedDependencyGraphItem.Path[childResolvedDependencyGraphItem.Path.Length - 1],
ToLibraryDependencyIndex: childLibraryDependencyIndex,
IsCentralTransitive: isCentralPackageTransitivePinningEnabled ? childResolvedDependencyGraphItem.IsCentrallyPinnedTransitivePackage : false
));
}
}
// Ignore this child dependency since it was a downgrade
continue;
}
// If it wasn't a downgrade, then it was a version conflict like A -> B [1.0.0] but B 1.0.0 was not in the resolved graph
if (versionConflicts.ContainsKey(childResolvedLibraryRangeIndex) && !nodesById.ContainsKey(currentRangeIndex))
{
GraphNode<RemoteResolveResult> nodeWithConflict = new(childResolvedLibraryDependency.LibraryRange)
{
Item = childResolvedDependencyGraphItem.Item,
Disposition = Disposition.Acceptable,
OuterNode = currentGraphNode,
};
currentGraphNode.InnerNodes.Add(nodeWithConflict);
nodesById.Add(currentRangeIndex, nodeWithConflict);
continue;
}
// Ignore this child dependency since it was not a cycle, downgrade, or version conflict but was already visited
continue;
}
// Create a GraphNode for the item
GraphNode<RemoteResolveResult> newGraphNode = new(childResolvedLibraryDependency.LibraryRange)
{
Item = childResolvedDependencyGraphItem.Item
};
if (childResolvedDependencyGraphItem.IsCentrallyPinnedTransitivePackage && !childResolvedDependencyGraphItem.IsRootPackageReference)
{
// If this child is transitively pinned, the GraphNode needs to have certain properties set
newGraphNode.Disposition = Disposition.Accepted;
newGraphNode.Item.IsCentralTransitive = true;
// Treat the transitively pinned dependency as a child of the root node
newGraphNode.OuterNode = rootGraphNode;
rootGraphNode.InnerNodes.Add(newGraphNode);
}
else
{
// Set properties for the node to represent a parent/child relationship
newGraphNode.OuterNode = currentGraphNode;
currentGraphNode.InnerNodes.Add(newGraphNode);
}
if (!childResolvedDependencyGraphItem.IsRootPackageReference && isCentralPackageTransitivePinningEnabled && childLibraryDependency.SuppressParent != LibraryIncludeFlags.All && !downgrades.ContainsKey(childResolvedLibraryRangeIndex) && !RemoteDependencyWalker.IsGreaterThanOrEqualTo(childResolvedDependencyGraphItem.LibraryDependency.LibraryRange.VersionRange, childLibraryDependency.LibraryRange.VersionRange))
{
// This is a downgrade if:
// 1. This is not a direct dependency
// 2. This is a central transitive pinned dependency
// 3. This is a transitive dependency which is not PrivateAssets=All
// 4. This has not already been detected
// 5. The version is lower
downgrades.Add(
childResolvedDependencyGraphItem.LibraryRangeIndex,
(
FromParentLibraryRangeIndex: currentLibraryRangeIndex,
FromLibraryDependency: childLibraryDependency,
ToParentLibraryRangeIndex: LibraryRangeIndex.Project,
ToLibraryDependencyIndex: childLibraryDependencyIndex,
IsCentralTransitive: true
));
}
// This is a version conflict if:
// 1. The node is not a project and isn't unresolved
// 2. The conflict has not already been detected
// 3. The dependency is transitive and doesn't have PrivateAssets=All
// 4. The dependency has a version specified
// 5. The version range is not satisfied by the resolved version
// 6. A corresponding downgrade was not detected
if (newGraphNode.Item.Key.Type != LibraryType.Project
&& newGraphNode.Item.Key.Type != LibraryType.ExternalProject
&& newGraphNode.Item.Key.Type != LibraryType.Unresolved
&& !versionConflicts.ContainsKey(childResolvedLibraryRangeIndex)
&& childLibraryDependency.SuppressParent != LibraryIncludeFlags.All
&& childLibraryDependency.LibraryRange.VersionRange != null
&& !childLibraryDependency.LibraryRange.VersionRange!.Satisfies(newGraphNode.Item.Key.Version)
&& !downgrades.ContainsKey(childResolvedLibraryRangeIndex))
{
// Remove the existing node so it can be replaced with a node representing the conflict
currentGraphNode.InnerNodes.Remove(newGraphNode);
GraphNode<RemoteResolveResult> conflictingNode = new(childLibraryDependency.LibraryRange)
{
Disposition = Disposition.Acceptable,
Item = new GraphItem<RemoteResolveResult>(
new LibraryIdentity(
childLibraryDependency.Name,
childLibraryDependency.LibraryRange.VersionRange.MinVersion!,
LibraryType.Package)),
OuterNode = currentGraphNode,
};
// Add the conflict node to the parent
currentGraphNode.InnerNodes.Add(conflictingNode);
// Track the version conflict for later
versionConflicts.Add(childResolvedLibraryRangeIndex, conflictingNode);
// Process the next child
continue;
}
// Add the node to the lookup for later
nodesById.Add(childResolvedLibraryRangeIndex, newGraphNode);
// Enqueue the child for processing
itemsToFlatten.Enqueue((childLibraryDependencyIndex, childResolvedLibraryRangeIndex, newGraphNode));
if (newGraphNode.Item.Key.Type == LibraryType.Unresolved)
{
// Keep track of unresolved packages and fail the restore
unresolvedPackages.Add(childResolvedLibraryDependency.LibraryRange);
success = false;
}
else
{
// Keep track of the resolved packages
resolvedPackages.Add(new ResolvedDependencyKey(
parent: newGraphNode.OuterNode.Item.Key,
range: newGraphNode.Key.VersionRange,
child: newGraphNode.Item.Key));
}
}
} // End of walking all declared dependencies for cycles, downgrades, and conflicts
// Add applicable version conflicts to the analyze results
if (versionConflicts.Count > 0)
{
foreach (KeyValuePair<LibraryRangeIndex, GraphNode<RemoteResolveResult>> versionConflict in versionConflicts)
{
if (nodesById.TryGetValue(versionConflict.Key, out GraphNode<RemoteResolveResult>? selected))
{
analyzeResult.VersionConflicts.Add(
new VersionConflictResult<RemoteResolveResult>
{
Conflicting = versionConflict.Value,
Selected = selected,
});
}
}
}
// Add applicable downgrades to the analyze results
if (downgrades.Count > 0)
{
foreach ((LibraryRangeIndex FromParentLibraryRangeIndex, LibraryDependency FromLibraryDependency, LibraryRangeIndex ToParentLibraryRangeIndex, LibraryDependencyIndex ToLibraryDependencyIndex, bool IsCentralTransitive) downgrade in downgrades.Values)
{
// Ignore the downgrade if a node was not created for its from or to, or if it never ended up in the resolved graph. Sometimes a downgrade is detected but later during graph
// resolution it is resolved so this verifies if the downgrade ended up in the final graph
if (!nodesById.TryGetValue(downgrade.FromParentLibraryRangeIndex, out GraphNode<RemoteResolveResult>? fromParentNode)
|| !nodesById.TryGetValue(downgrade.ToParentLibraryRangeIndex, out GraphNode<RemoteResolveResult>? toParentNode)
|| !resolvedDependencyGraphItems.TryGetValue(downgrade.ToLibraryDependencyIndex, out ResolvedDependencyGraphItem? toResolvedDependencyGraphItem))
{
continue;
}
// Add the downgrade
analyzeResult.Downgrades.Add(new DowngradeResult<RemoteResolveResult>
{
DowngradedFrom = new GraphNode<RemoteResolveResult>(downgrade.FromLibraryDependency.LibraryRange)
{
Item = new GraphItem<RemoteResolveResult>(
new LibraryIdentity(
downgrade.FromLibraryDependency.Name,
downgrade.FromLibraryDependency.LibraryRange.VersionRange?.MinVersion!,
LibraryType.Package)),
OuterNode = fromParentNode
},
DowngradedTo = new GraphNode<RemoteResolveResult>(toResolvedDependencyGraphItem.LibraryDependency.LibraryRange)
{
Item = new GraphItem<RemoteResolveResult>(toResolvedDependencyGraphItem.Item.Key)
{
IsCentralTransitive = downgrade.IsCentralTransitive
},
OuterNode = downgrade.IsCentralTransitive ? rootGraphNode : toParentNode,
}
});
}
}
// If central transitive pinning is enabled, we need to add all of its parent nodes. This has to happen at the end after all of the nodes in graph have been created
if (isCentralPackageTransitivePinningEnabled)
{
foreach (KeyValuePair<LibraryDependencyIndex, ResolvedDependencyGraphItem> resolvedDependencyGraphItemEntry in resolvedDependencyGraphItems)
{
ResolvedDependencyGraphItem resolvedDependencyGraphItem = resolvedDependencyGraphItemEntry.Value;
// Skip this item if:
// 1. It is not pinned
// 2. It is a direct package reference
// 3. It has not parents
// 4. A node was not created for it
if (!resolvedDependencyGraphItem.IsCentrallyPinnedTransitivePackage
|| resolvedDependencyGraphItem.IsRootPackageReference
|| resolvedDependencyGraphItem.Parents == null
|| resolvedDependencyGraphItem.Parents.Count == 0
|| !nodesById.TryGetValue(resolvedDependencyGraphItem.LibraryRangeIndex, out GraphNode<RemoteResolveResult>? currentNode))
{
continue;
}
// Get the corresponding node in the graph for each parent and add it the list of parent nodes
foreach (LibraryRangeIndex parentLibraryRangeIndex in resolvedDependencyGraphItem.Parents.NoAllocEnumerate())
{
if (!nodesById.TryGetValue(parentLibraryRangeIndex, out GraphNode<RemoteResolveResult>? parentNode))
{
// Skip nodes that weren't created
continue;
}
currentNode.ParentNodes.Add(parentNode);
}
}
}
// Get the list of packages to install
HashSet<RemoteMatch> packagesToInstall = await context.GetUnresolvedRemoteMatchesAsync();
// Create a RestoreTargetGraph with all of the information
RestoreTargetGraph restoreTargetGraph = new(
Array.Empty<ResolverConflict>(),
frameworkRuntimePair.Framework,
string.IsNullOrWhiteSpace(frameworkRuntimePair.RuntimeIdentifier) ? null : frameworkRuntimePair.RuntimeIdentifier,
runtimeGraph,
graphNodes,
install: packagesToInstall,
flattened: flattenedGraphItems,
unresolved: unresolvedPackages,
analyzeResult,
resolvedDependencies: resolvedPackages);
return (success, restoreTargetGraph);
}
private static bool EvaluateRuntimeDependencies(ref LibraryDependency libraryDependency, RuntimeGraph? runtimeGraph, string? runtimeIdentifier, ref HashSet<LibraryDependency>? runtimeDependencies)
{
LibraryRange libraryRange = libraryDependency.LibraryRange;
if (runtimeGraph == null || string.IsNullOrEmpty(runtimeIdentifier) || !RemoteDependencyWalker.EvaluateRuntimeDependencies(ref libraryRange, runtimeIdentifier, runtimeGraph, ref runtimeDependencies))
{
return false;
}
libraryDependency = new LibraryDependency(libraryDependency)
{
LibraryRange = libraryRange
};
return true;
}
private static bool HasCommonAncestor(LibraryRangeIndex[] left, LibraryRangeIndex[] right)
{
for (int i = 0; i < left.Length && i < right.Length; i++)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determine if the chosen item should be evicted based on the <see cref="LibraryRange.TypeConstraint" />.
/// </summary>
/// <remarks>
/// We should evict on type constraint if the type constraint of the current item has the same version but has a more restrictive type constraint than the chosen item.
/// This happens when the chosen item's type constraint is broader (e.g. PackageProjectExternal) than the current item's type constraint (e.g. Package).
/// </remarks>
/// <returns></returns>
private static bool ShouldEvictOnTypeConstraint(DependencyGraphItem currentDependencyGraphItem, ResolvedDependencyGraphItem resolvedDependencyGraphItem)
{
LibraryDependency currentLibraryDependency = currentDependencyGraphItem.LibraryDependency;
LibraryDependency chosenLibraryDependency = resolvedDependencyGraphItem.LibraryDependency;
// We should evict the chosen item if it is a package but the current item is a project since projects should be chosen over packages
if (chosenLibraryDependency.LibraryRange.TypeConstraint == LibraryDependencyTarget.PackageProjectExternal
&& currentLibraryDependency.LibraryRange.TypeConstraint == LibraryDependencyTarget.ExternalProject)
{
return true;
}
LibraryRangeIndex currentLibraryRangeIndex = currentDependencyGraphItem.LibraryRangeIndex;
LibraryRangeIndex chosenLibraryRangeIndex = resolvedDependencyGraphItem.LibraryRangeIndex;
// Do not evict if:
// 1. The current item and chosen item are not the same version
// 2. The current item and chosen item have the same type constraint
// 3. The chosen item has a strict type constraint instead of the more generic "PackageProjectExternal"
if (currentLibraryRangeIndex != chosenLibraryRangeIndex
|| currentLibraryDependency.LibraryRange.TypeConstraint == chosenLibraryDependency.LibraryRange.TypeConstraint
|| chosenLibraryDependency.LibraryRange.TypeConstraint != LibraryDependencyTarget.PackageProjectExternal)
{
return false;
}
LibraryDependencyTarget packageProjectExternalFlags = currentLibraryDependency.LibraryRange.TypeConstraint & LibraryDependencyTarget.PackageProjectExternal;
LibraryDependencyTarget nonPackageProjectExternalFlats = currentLibraryDependency.LibraryRange.TypeConstraint & ~LibraryDependencyTarget.PackageProjectExternal;
// Evict if the type constraint of the current item is more precise than "PackageProjectExternal" and the current item is a project
if (packageProjectExternalFlags != LibraryDependencyTarget.None && nonPackageProjectExternalFlats == LibraryDependencyTarget.None)
{
return resolvedDependencyGraphItem.Item.Key.Type == LibraryType.Project;
}
return false;
}
private static bool VersionRangePreciseEquals(VersionRange a, VersionRange b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if ((a.MinVersion != null) != (b.MinVersion != null))
{
return false;
}
if (a.MinVersion != b.MinVersion)
{
return false;
}
if ((a.MaxVersion != null) != (b.MaxVersion != null))
{
return false;
}
if (a.MaxVersion != b.MaxVersion)
{
return false;
}
if (a.IsMinInclusive != b.IsMinInclusive)
{
return false;
}
if (a.IsMaxInclusive != b.IsMaxInclusive)
{
return false;
}
if ((a.Float != null) != (b.Float != null))
{
return false;
}
if (a.Float != b.Float)
{
return false;
}
return true;
}
/// <summary>
/// Indexes all central package versions if central transitive pinning is enabled.
/// </summary>
/// <param name="isCentralPackageTransitivePinningEnabled">Indicates whether or not central transitive pinning is enabled.</param>
/// <param name="projectTargetFramework">The <see cref="TargetFrameworkInformation" /> of the project.</param>
/// <returns>A <see cref="Dictionary{TKey, TValue}" /> of indexed version ranges by their <see cref="LibraryDependencyIndex" /> if central transitive pinning is enabled, otherwise <see langword="null" />.</returns>
private Dictionary<LibraryDependencyIndex, VersionRange>? IndexPinnedPackageVersions(bool isCentralPackageTransitivePinningEnabled, TargetFrameworkInformation? projectTargetFramework)
{
if (!isCentralPackageTransitivePinningEnabled || projectTargetFramework == null || projectTargetFramework.CentralPackageVersions == null)
{
return null;
}
Dictionary<LibraryDependencyIndex, VersionRange>? pinnedPackageVersions = new(capacity: projectTargetFramework.CentralPackageVersions.Count);
foreach (KeyValuePair<string, CentralPackageVersion> item in projectTargetFramework.CentralPackageVersions.NoAllocEnumerate())
{
LibraryDependencyIndex libraryDependencyIndex = _indexingTable.Index(item.Value);
pinnedPackageVersions[libraryDependencyIndex] = item.Value.VersionRange;
}
return pinnedPackageVersions;
}
private async Task<Dictionary<LibraryDependencyIndex, ResolvedDependencyGraphItem>> ResolveDependencyGraphItemsAsync(
bool isCentralPackageTransitivePinningEnabled,
FrameworkRuntimePair pair,
TargetFrameworkInformation? projectTargetFramework,
RuntimeGraph? runtimeGraph,
Dictionary<LibraryDependencyIndex,
VersionRange>? pinnedPackageVersions,
DependencyGraphItem rootProjectDependencyGraphItem,
RemoteWalkContext context,
CancellationToken token)
{
// Stores the resolved dependency graph items
Dictionary<LibraryDependencyIndex, ResolvedDependencyGraphItem> resolvedDependencyGraphItems = new(ResolvedDependencyGraphItemDictionarySize);
// Stores a list of direct package references by their LibraryDependencyIndex so that we can quickly determine if a transitive package can be ignored
HashSet<LibraryDependencyIndex>? directPackageReferences = default;
// Stores the queue of DependencyGraphItem objects to process
Queue<DependencyGraphItem> dependencyGraphItemQueue = new(DependencyGraphItemQueueSize);
// Stores any evictions to process
Dictionary<LibraryRangeIndex, (LibraryRangeIndex[], LibraryDependencyIndex, LibraryDependencyTarget)> evictions = new Dictionary<LibraryRangeIndex, (LibraryRangeIndex[], LibraryDependencyIndex, LibraryDependencyTarget)>(EvictionsDictionarySize);
// Used to start over when a dependency has multiple descendants of an item to be evicted.
//
// Project
// ├── A 1.0.0
// │ └── B 1.0.0
// │ └── C 1.0.0
// │ └── D 1.0.0
// └── X 2.0.0
// └── Y 2.0.0
// └── G 2.0.0
// └── B 2.0.0
// The items are processed in the following order:
// Chose A 1.0.0 and X 1.0.0
// Chose B 1.0.0 and Y 2.0.0
// Chose C 1.0.0 and G 2.0.0
// Chose D 1.0.0 and B 2.0.0, but B 2.0.0 should evict C 1.0.0 and D 1.0.0
//
// In this case, the entire walk is started over and B 1.0.0 is left out of the graph, leading to C 1.0.0 and D 1.0.0 also being left out.
//
StartOver:
dependencyGraphItemQueue.Clear();
resolvedDependencyGraphItems.Clear();
dependencyGraphItemQueue.Enqueue(rootProjectDependencyGraphItem);
while (dependencyGraphItemQueue.Count > 0)
{
DependencyGraphItem currentDependencyGraphItem = dependencyGraphItemQueue.Dequeue();
// Determine if what is being processed is the root project itself which has different rules vs a transitive dependency
bool isRootProject = currentDependencyGraphItem.LibraryDependencyIndex == LibraryDependencyIndex.Project;
GraphItem<RemoteResolveResult> currentGraphItem = await currentDependencyGraphItem.GetGraphItemAsync(_request.Project.RestoreMetadata, projectTargetFramework?.PackagesToPrune, isRootProject, _logger);
LibraryDependencyTarget typeConstraint = currentDependencyGraphItem.LibraryDependency.LibraryRange.TypeConstraint;
if (evictions.TryGetValue(currentDependencyGraphItem.LibraryRangeIndex, out (LibraryRangeIndex[], LibraryDependencyIndex, LibraryDependencyTarget) eviction))
{
(LibraryRangeIndex[] evictedPath, LibraryDependencyIndex evictedDepIndex, LibraryDependencyTarget evictedTypeConstraint) = eviction;
// If we evicted this same version previously, but the type constraint of currentRef is more stringent (package), then do not skip the current item - this is the one we want.
// This is tricky. I don't really know what this means. Normally we'd key off of versions instead.
if (!((evictedTypeConstraint == LibraryDependencyTarget.PackageProjectExternal || evictedTypeConstraint == LibraryDependencyTarget.ExternalProject) &&
currentDependencyGraphItem.LibraryDependency.LibraryRange.TypeConstraint == LibraryDependencyTarget.Package))
{
continue;
}
}
// Determine if a dependency with the same name has not already been chosen
if (!resolvedDependencyGraphItems.TryGetValue(currentDependencyGraphItem.LibraryDependencyIndex, out ResolvedDependencyGraphItem? chosenResolvedItem))
{
// Create a resolved dependency graph item and add it to the list of chosen items
chosenResolvedItem = new ResolvedDependencyGraphItem(currentGraphItem, currentDependencyGraphItem, _indexingTable)
{
Parents = currentDependencyGraphItem.IsCentrallyPinnedTransitivePackage && !currentDependencyGraphItem.IsRootPackageReference ? new HashSet<LibraryRangeIndex>() { currentDependencyGraphItem.Parent } : null,
IsCentrallyPinnedTransitivePackage = currentDependencyGraphItem.IsCentrallyPinnedTransitivePackage,
IsRootPackageReference = currentDependencyGraphItem.IsRootPackageReference,
Suppressions = new List<HashSet<LibraryDependencyIndex>>
{
currentDependencyGraphItem.Suppressions!
}
};
resolvedDependencyGraphItems.Add(currentDependencyGraphItem.LibraryDependencyIndex, chosenResolvedItem);
}
else // A dependency with the same name has already been chosen so we need to decide what to do with it
{
if (chosenResolvedItem.IsRootPackageReference)
{
// If the chosen dependency graph item is a direct dependency, it should always be chosen regardless of version so do not process this dependency
continue;
}
if (chosenResolvedItem.LibraryDependency.LibraryRange.TypeConstraint == LibraryDependencyTarget.ExternalProject
&& currentDependencyGraphItem.LibraryDependency.LibraryRange.TypeConstraintAllows(LibraryDependencyTarget.Package)
&& currentGraphItem.Key.Type == LibraryType.Project)
{
// If the chosen dependency graph item is a project reference, it should always be chosen over a package reference. In this case, a project has already been chosen
// for the graph with the same name as a transitive package reference, so this item does not need to be processed.
continue;
}
// Determine if the chosen item should be evicted based on type constraint.
bool evictOnTypeConstraint = ShouldEvictOnTypeConstraint(currentDependencyGraphItem, chosenResolvedItem);
VersionRange currentVersionRange = currentDependencyGraphItem.LibraryDependency.LibraryRange.VersionRange ?? VersionRange.All;
VersionRange chosenVersionRange = chosenResolvedItem.LibraryDependency.LibraryRange.VersionRange ?? VersionRange.All;
// The chosen item should be evicted or the current item has a greater version, determine if the current item should be chosen instead
if (evictOnTypeConstraint || !RemoteDependencyWalker.IsGreaterThanOrEqualTo(chosenVersionRange, currentVersionRange))