private static async Task <RestoreTargetGraph> GetPlatformSpecificGraph(RestoreTargetGraph independentGraph,
                                                                                string package, string version, NuGetFramework framework, string runtimeIdentifier,
                                                                                RemoteWalkContext context, LocalPackageExtractor extractor)
        {
            var graphTask = independentGraph.Flattened
                            .Where(m => m.Data?.Match?.Library?.Type == LibraryType.Package)
                            .Select(GetRuntimeGraphTask);

            var graphs = (await Task.WhenAll(graphTask))
                         .Where(i => i != null);

            var runtimeGraph = graphs.Aggregate(RuntimeGraph.Empty, RuntimeGraph.Merge);

            // This results in additional entries
            var resultWin = await new RemoteDependencyWalker(context).WalkAsync(
                new LibraryRange(package, VersionRange.Parse(version), LibraryDependencyTarget.All),
                framework,
                runtimeGraph: runtimeGraph,
                recursive: true,
                runtimeIdentifier: runtimeIdentifier);

            return(RestoreTargetGraph.Create(runtimeGraph, new[]
            {
                resultWin
            }, context, context.Logger, framework, runtimeIdentifier));

            async Task <RuntimeGraph> GetRuntimeGraphTask(GraphItem <RemoteResolveResult> item)
            {
                var packageIdentity = ToPackageIdentity(item.Data.Match);

                var localPackageSourceInfo = await extractor.EnsureLocalPackage(item.Data.Match.Provider, packageIdentity);

                return(localPackageSourceInfo?.Package?.RuntimeGraph);
            }
        }
Beispiel #2
0
        private void DetectMissingTransitiveDependencies(List <PackageReference> packages, string projectPath)
        {
            List <NuGetFramework> targetFrameworks = new List <NuGetFramework>
            {
                FrameworkConstants.CommonFrameworks.Net45
            };

            using (SourceCacheContext sourceCacheContext = new SourceCacheContext
            {
                IgnoreFailedSources = true,
            })
            {
                RestoreTargetGraph restoreTargetGraph = GetRestoreTargetGraph(packages, projectPath, targetFrameworks, sourceCacheContext);

                if (restoreTargetGraph != null)
                {
                    var flatPackageDependencies = restoreTargetGraph.Flattened.Where(i => i.Key.Type == LibraryType.Package);
                    foreach (var packageDependency in flatPackageDependencies)
                    {
                        var(library, metadata) = (packageDependency.Key, packageDependency.Data);
                        PackageReference packageReference = packages.FirstOrDefault(i => i.PackageId.Equals(library.Name, StringComparison.OrdinalIgnoreCase));

                        if (packageReference == null)
                        {
                            Log.Warn($"{projectPath}: The transitive package dependency \"{library.Name} {library.Version}\" was not in the packages.config.  After converting to PackageReference, new dependencies will be pulled in transitively which could lead to restore or build errors");

                            packages.Add(new PackageReference(new PackageIdentity(library.Name, library.Version), NuGetFramework.AnyFramework, true, false, true, new VersionRange(library.Version), PackagePathResolver, VersionFolderPathResolver)
                            {
                                IsMissingTransitiveDependency = true
                            });
                        }
                    }
                }
            }
        }
        public static RestoreTargetGraph GetRestoreTargetGraph(
            string source,
            PackageIdentity identity,
            FileInfo packagePath,
            TestLogger logger)
        {
            var libraryRange = new LibraryRange {
                Name = identity.Id
            };
            var libraryIdentity = new LibraryIdentity(identity.Id, identity.Version, LibraryType.Package);

            var dependencyProvider = new Mock <IRemoteDependencyProvider>();
            IPackageDownloader packageDependency = null;

            dependencyProvider
            .Setup(x => x.GetPackageDownloaderAsync(
                       It.IsAny <PackageIdentity>(),
                       It.IsAny <SourceCacheContext>(),
                       It.IsAny <ILogger>(),
                       It.IsAny <CancellationToken>()))
            .Callback <PackageIdentity, SourceCacheContext, ILogger, CancellationToken>(
                (callbackIdentity, sourceCacheContext, callbackLogger, cancellationToken) =>
            {
                packageDependency = new LocalPackageArchiveDownloader(
                    source,
                    packagePath.FullName,
                    callbackIdentity,
                    callbackLogger);
            })
            .Returns(() => Task.FromResult(packageDependency));

            var graph = RestoreTargetGraph.Create(
                new[]
            {
                new GraphNode <RemoteResolveResult>(libraryRange)
                {
                    Item = new GraphItem <RemoteResolveResult>(libraryIdentity)
                    {
                        Data = new RemoteResolveResult
                        {
                            Match = new RemoteMatch
                            {
                                Library  = libraryIdentity,
                                Provider = dependencyProvider.Object
                            }
                        }
                    }
                }
            },
                new TestRemoteWalkContext(),
                logger,
                FrameworkConstants.CommonFrameworks.NetStandard16);

            return(graph);
        }
Beispiel #4
0
        private async Task <RestoreTargetGraph> GenerateRestoreGraph(ILogger log, string projectName, string projectPath)
        {
            var dgFile = await VSProjectHelper.GenerateRestoreGraphFile(log, projectPath);

            var dgProvider = new DependencyGraphSpecRequestProvider(new RestoreCommandProvidersCache(), dgFile);

            using (var cacheContext = new SourceCacheContext())
            {
                var restoreContext = new RestoreArgs();
                restoreContext.CacheContext = cacheContext;
                restoreContext.Log          = new NuGet.Common.NullLogger();
                restoreContext.PreLoadedRequestProviders.Add(dgProvider);

                var request = (await dgProvider.CreateRequests(restoreContext)).Single();

                var restoreRequest    = request.Request;
                var collectorLogger   = new RestoreCollectorLogger(restoreRequest.Log, false);
                var contextForProject = CreateRemoteWalkContext(restoreRequest, collectorLogger);

                // Get external project references
                // If the top level project already exists, update the package spec provided
                // with the RestoreRequest spec.
                var updatedExternalProjects = GetProjectReferences(restoreRequest, contextForProject);

                // Load repositories
                // the external project provider is specific to the current restore project
                contextForProject.ProjectLibraryProviders.Add(new PackageSpecReferenceDependencyProvider(updatedExternalProjects, restoreRequest.Log));


                var walker = new RemoteDependencyWalker(contextForProject);

                var requestProject = request.Request.Project;

                var projectRange = new LibraryRange()
                {
                    Name           = projectName,
                    VersionRange   = new NuGet.Versioning.VersionRange(requestProject.Version),
                    TypeConstraint = LibraryDependencyTarget.Project | LibraryDependencyTarget.ExternalProject
                };

                var framework = requestProject.TargetFrameworks.First();
                var graphs    = new List <GraphNode <RemoteResolveResult> >
                {
                    await walker.WalkAsync(
                        projectRange,
                        framework.FrameworkName,
                        null,
                        RuntimeGraph.Empty,
                        recursive : true)
                };
                return(RestoreTargetGraph.Create(graphs, contextForProject, restoreRequest.Log, framework.FrameworkName));
            }
        }
        private async Task <RestoreTargetGraph> GetIndependentGraph(string package, string version, NuGetFramework nuGetFramework, RemoteWalkContext context)
        {
            var result = await new RemoteDependencyWalker(context).WalkAsync(
                new LibraryRange(package, VersionRange.Parse(version), LibraryDependencyTarget.All),
                nuGetFramework,
                runtimeGraph: RuntimeGraph.Empty,
                recursive: true,
                runtimeIdentifier: null);

            return(RestoreTargetGraph.Create(RuntimeGraph.Empty, new[]
            {
                result
            }, _context, _context.Logger, nuGetFramework, runtimeIdentifier: null));
        }
Beispiel #6
0
        private static RestoreTargetGraph GetRestoreTargetGraph(PackageIdentity identity, FileInfo packagePath, TestLogger logger)
        {
            var libraryRange = new LibraryRange {
                Name = identity.Id
            };
            var libraryIdentity = new LibraryIdentity(identity.Id, identity.Version, LibraryType.Package);

            var dependencyProvider = new Mock <IRemoteDependencyProvider>();

            dependencyProvider
            .Setup(x => x.CopyToAsync(
                       It.IsAny <LibraryIdentity>(),
                       It.IsAny <Stream>(),
                       It.IsAny <SourceCacheContext>(),
                       It.IsAny <ILogger>(),
                       It.IsAny <CancellationToken>()))
            .Callback <LibraryIdentity, Stream, SourceCacheContext, ILogger, CancellationToken>(
                (_, destination, __, ___, ____) =>
            {
                using (var package = File.OpenRead(packagePath.FullName))
                {
                    package.CopyTo(destination);
                }
            })
            .Returns(Task.CompletedTask);

            var graph = RestoreTargetGraph.Create(
                new[]
            {
                new GraphNode <RemoteResolveResult>(libraryRange)
                {
                    Item = new GraphItem <RemoteResolveResult>(libraryIdentity)
                    {
                        Data = new RemoteResolveResult
                        {
                            Match = new RemoteMatch
                            {
                                Library  = libraryIdentity,
                                Provider = dependencyProvider.Object
                            }
                        }
                    }
                }
            },
                new TestRemoteWalkContext(),
                logger,
                FrameworkConstants.CommonFrameworks.NetStandard16);

            return(graph);
        }
 public async Task <IReadOnlyCollection <LocalPackageSourceInfo> > DownloadPackages(RestoreTargetGraph dependencyGraph)
 {
     return(await Task.WhenAll(dependencyGraph.Flattened
                               .Where(i => !string.Equals(i.Key.Name, _rootProjectName, StringComparison.OrdinalIgnoreCase))
                               .Select(DownloadPackage)));
 }
Beispiel #8
0
            public RestoreResult GetRestoreResult(IEnumerable <PackageIdentity> identities)
            {
                var node = new GraphNode <RemoteResolveResult>(new LibraryRange("project", LibraryDependencyTarget.All))
                {
                    Item = new GraphItem <RemoteResolveResult>(
                        new LibraryIdentity(
                            "project",
                            new NuGetVersion("1.0.0"),
                            LibraryType.Project))
                    {
                        Data = new RemoteResolveResult
                        {
                            Match = new RemoteMatch
                            {
                                Provider = null
                            }
                        }
                    }
                };

                foreach (var identity in identities)
                {
                    var dependencyNode = new GraphNode <RemoteResolveResult>(
                        new LibraryRange(
                            identity.Id,
                            new VersionRange(identity.Version),
                            LibraryDependencyTarget.All))
                    {
                        Item = new GraphItem <RemoteResolveResult>(
                            new LibraryIdentity(
                                identity.Id,
                                identity.Version,
                                LibraryType.Package))
                        {
                            Data = new RemoteResolveResult
                            {
                                Match = new RemoteMatch
                                {
                                    Provider = null
                                }
                            }
                        }
                    };

                    dependencyNode.OuterNode = node;
                    node.InnerNodes.Add(dependencyNode);
                }

                var graph = RestoreTargetGraph.Create(
                    new[] { node },
                    new TestRemoteWalkContext(),
                    NullLogger.Instance,
                    FrameworkConstants.CommonFrameworks.NetStandard10);

                return(new RestoreResult(
                           true,
                           new[] { graph },
                           null,
                           null,
                           null,
                           null,
                           null,
                           null,
                           null,
                           null,
                           null,
                           ProjectStyle.Unknown,
                           TimeSpan.MinValue));
            }
Beispiel #9
0
        private RestoreTargetGraph GetRestoreTargetGraph(List <PackageReference> packages, string projectPath, List <NuGetFramework> targetFrameworks, SourceCacheContext sourceCacheContext)
        {
            // The package spec details what packages to restore
            PackageSpec packageSpec = new PackageSpec(targetFrameworks.Select(i => new TargetFrameworkInformation
            {
                FrameworkName = i
            }).ToList())
            {
                //Dependencies = new List<LibraryDependency>
                //{
                //    new LibraryDependency
                //    {
                //        LibraryRange = new LibraryRange(id, new VersionRange(NuGetVersion.Parse(version)), LibraryDependencyTarget.Package),
                //        SuppressParent = LibraryIncludeFlags.All,
                //        AutoReferenced = true,
                //        IncludeType = LibraryIncludeFlags.None,
                //        Type = LibraryDependencyType.Build
                //    }
                //},
                Dependencies = packages.Select(i => new LibraryDependency
                {
                    LibraryRange = new LibraryRange(i.PackageId, new VersionRange(i.PackageVersion), LibraryDependencyTarget.Package),
                    //SuppressParent = LibraryIncludeFlags.All,
                    //AutoReferenced = true,
                    //IncludeType = LibraryIncludeFlags.None,
                    //Type = LibraryDependencyType.
                }).ToList(),
                RestoreMetadata = new ProjectRestoreMetadata
                {
                    ProjectPath              = projectPath,
                    ProjectName              = Path.GetFileNameWithoutExtension(projectPath),
                    ProjectStyle             = ProjectStyle.PackageReference,
                    ProjectUniqueName        = projectPath,
                    OutputPath               = Path.GetTempPath(),
                    OriginalTargetFrameworks = targetFrameworks.Select(i => i.ToString()).ToList(),
                    ConfigFilePaths          = SettingsUtility.GetConfigFilePaths(_nugetSettings).ToList(),
                    PackagesPath             = SettingsUtility.GetGlobalPackagesFolder(_nugetSettings),
                    Sources         = SettingsUtility.GetEnabledSources(_nugetSettings).ToList(),
                    FallbackFolders = SettingsUtility.GetFallbackPackageFolders(_nugetSettings).ToList()
                },
                FilePath = projectPath,
                Name     = Path.GetFileNameWithoutExtension(projectPath),
            };

            DependencyGraphSpec dependencyGraphSpec = new DependencyGraphSpec();

            dependencyGraphSpec.AddProject(packageSpec);

            dependencyGraphSpec.AddRestore(packageSpec.RestoreMetadata.ProjectUniqueName);

            IPreLoadedRestoreRequestProvider requestProvider = new DependencyGraphSpecRequestProvider(new RestoreCommandProvidersCache(), dependencyGraphSpec);

            RestoreArgs restoreArgs = new RestoreArgs
            {
                AllowNoOp             = true,
                CacheContext          = sourceCacheContext,
                CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(_nugetSettings)),
                Log = NullLogger.Instance,
            };

            // Create requests from the arguments
            IReadOnlyList <RestoreSummaryRequest> requests = requestProvider.CreateRequests(restoreArgs).Result;

            // Restore the package without generating extra files
            RestoreResultPair restoreResult = RestoreRunner.RunWithoutCommit(requests, restoreArgs).Result.FirstOrDefault();

            RestoreTargetGraph restoreTargetGraph = restoreResult?.Result.RestoreGraphs.FirstOrDefault();

            return(restoreTargetGraph);
        }
 public TargetGraphLookup(RestoreTargetGraph graph)
 {
     _graph = graph;
 }