private async Task <RestoreTargetGraph?> RestoreProjectAsync(IEnumerable <NuGetReference> packages, IEnumerable <TargetFrameworkMoniker> tfms, CancellationToken token)
        {
            var tfmInfo = tfms.Select(tfm => new TargetFrameworkInformation {
                FrameworkName = NuGetFramework.Parse(tfm.ToFullString())
            }).ToList();

            // Create a project in a unique and temporary directory
            var path = Path.Combine(Path.GetTempPath(), "dotnet-ua", "restores", Guid.NewGuid().ToString(), "project.txt");

            var spec = new PackageSpec(tfmInfo)
            {
                Dependencies = packages.Select(i => new LibraryDependency
                {
                    LibraryRange = new LibraryRange(i.Name, new VersionRange(i.GetNuGetVersion()), LibraryDependencyTarget.Package),
                }).ToList(),
                RestoreMetadata = new()
                {
                    ProjectPath              = path,
                    ProjectName              = Path.GetFileNameWithoutExtension(path),
                    ProjectStyle             = ProjectStyle.PackageReference,
                    ProjectUniqueName        = path,
                    OutputPath               = Path.GetTempPath(),
                    OriginalTargetFrameworks = tfms.Select(tfm => tfm.ToFullString()).ToArray(),
                    ConfigFilePaths          = _settings.GetConfigFilePaths(),
                    PackagesPath             = SettingsUtility.GetGlobalPackagesFolder(_settings),
                    Sources         = _packageSources.ToList(),
                    FallbackFolders = SettingsUtility.GetFallbackPackageFolders(_settings).ToList(),
                },
                FilePath = path,
                Name     = Path.GetFileNameWithoutExtension(path),
            };

            var dependencyGraphSpec = new DependencyGraphSpec();

            dependencyGraphSpec.AddProject(spec);
            dependencyGraphSpec.AddRestore(spec.RestoreMetadata.ProjectUniqueName);

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

            var restoreArgs = new RestoreArgs
            {
                AllowNoOp             = true,
                CacheContext          = _context,
                CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(_settings)),
                Log = new NuGetLogger(_logger),
            };

            // Create requests from the arguments
            var requests = await requestProvider.CreateRequests(restoreArgs).ConfigureAwait(false);

            // Restore the package without generating extra files
            var result = await RestoreRunner.RunWithoutCommit(requests, restoreArgs).ConfigureAwait(false);

            if (result.Count == 0)
            {
                return(null);
            }

            return(result[0].Result.RestoreGraphs.FirstOrDefault());
        }
        /// <summary>
        /// Restore many projects without writing the lock file
        /// SourceRepositories(sources) is only used for the CachingSourceProvider, the project-specific sources will still be resolved in RestoreRunner.
        /// </summary>
        internal static async Task <IEnumerable <RestoreResultPair> > PreviewRestoreProjectsAsync(
            ISolutionManager solutionManager,
            IEnumerable <BuildIntegratedNuGetProject> projects,
            IEnumerable <PackageSpec> updatedNugetPackageSpecs,
            DependencyGraphCacheContext context,
            RestoreCommandProvidersCache providerCache,
            Action <SourceCacheContext> cacheContextModifier,
            IEnumerable <SourceRepository> sources,
            Guid parentId,
            ILogger log,
            CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            // Add the new spec to the dg file and fill in the rest.
            var dgFile = await GetSolutionRestoreSpec(solutionManager, context);

            dgFile = dgFile.WithoutRestores()
                     .WithPackageSpecs(updatedNugetPackageSpecs);

            foreach (var project in projects)
            {
                dgFile.AddRestore(project.MSBuildProjectPath);
            }

            using (var sourceCacheContext = new SourceCacheContext())
            {
                // Update cache context
                cacheContextModifier(sourceCacheContext);

                // Settings passed here will be used to populate the restore requests.
                var restoreContext = GetRestoreArgs(
                    context,
                    providerCache,
                    sourceCacheContext,
                    sources,
                    dgFile,
                    parentId,
                    forceRestore: true,
                    isRestoreOriginalAction: false,
                    restoreForceEvaluate: true,
                    additionalMessasges: null,
                    progressReporter: null);

                var requests = await RestoreRunner.GetRequests(restoreContext);

                var results = await RestoreRunner.RunWithoutCommit(requests, restoreContext);

                return(results);
            }
        }
        /// <summary>
        /// Restore without writing the lock file
        /// </summary>
        internal static async Task <RestoreResultPair> PreviewRestoreAsync(
            ISolutionManager solutionManager,
            BuildIntegratedNuGetProject project,
            PackageSpec packageSpec,
            DependencyGraphCacheContext context,
            RestoreCommandProvidersCache providerCache,
            Action <SourceCacheContext> cacheContextModifier,
            IEnumerable <SourceRepository> sources,
            Guid parentId,
            ILogger log,
            CancellationToken token)
        {
            // Restoring packages
            var logger = context.Logger;

            // Add the new spec to the dg file and fill in the rest.
            var dgFile = await GetSolutionRestoreSpec(solutionManager, context);

            dgFile = dgFile.WithoutRestores()
                     .WithReplacedSpec(packageSpec);

            dgFile.AddRestore(project.MSBuildProjectPath);

            using (var sourceCacheContext = new SourceCacheContext())
            {
                // Update cache context
                cacheContextModifier(sourceCacheContext);

                // Settings passed here will be used to populate the restore requests.
                var restoreContext = GetRestoreContext(
                    context,
                    providerCache,
                    sourceCacheContext,
                    sources,
                    dgFile,
                    parentId,
                    forceRestore: true,
                    isRestoreOriginalAction: false,
                    restoreForceEvaluate: true,
                    additionalMessasges: null);

                var requests = await RestoreRunner.GetRequests(restoreContext);

                var results = await RestoreRunner.RunWithoutCommit(requests, restoreContext);

                return(results.Single());
            }
        }
        private static async Task <RestoreResultPair> PreviewAddPackageReference(PackageReferenceArgs packageReferenceArgs,
                                                                                 DependencyGraphSpec dgSpec,
                                                                                 PackageSpec originalPackageSpec)
        {
            // Set user agent and connection settings.
            XPlatUtility.ConfigureProtocol();

            var providerCache = new RestoreCommandProvidersCache();

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache             = false;
                cacheContext.IgnoreFailedSources = false;

                // Pre-loaded request provider containing the graph file
                var providers = new List <IPreLoadedRestoreRequestProvider>();

                // Create a copy to avoid modifying the original spec which may be shared.
                var updatedPackageSpec = originalPackageSpec.Clone();

                PackageSpecOperations.AddOrUpdateDependency(updatedPackageSpec, packageReferenceArgs.PackageDependency);

                providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dgSpec));

                var restoreContext = new RestoreArgs()
                {
                    CacheContext              = cacheContext,
                    LockFileVersion           = LockFileFormat.Version,
                    Log                       = packageReferenceArgs.Logger,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    GlobalPackagesFolder      = packageReferenceArgs.PackageDirectory,
                    PreLoadedRequestProviders = providers,
                    Sources                   = packageReferenceArgs.Sources?.ToList()
                };

                // Generate Restore Requests. There will always be 1 request here since we are restoring for 1 project.
                var restoreRequests = await RestoreRunner.GetRequests(restoreContext);

                // Run restore without commit. This will always return 1 Result pair since we are restoring for 1 request.
                var restoreResult = await RestoreRunner.RunWithoutCommit(restoreRequests, restoreContext);

                return(restoreResult.Single());
            }
        }
Beispiel #5
0
        private static async Task <RestoreResultPair> PreviewAddPackageReferenceAsync(PackageReferenceArgs packageReferenceArgs,
                                                                                      DependencyGraphSpec dgSpec)
        {
            // Set user agent and connection settings.
            XPlatUtility.ConfigureProtocol();

            var providerCache = new RestoreCommandProvidersCache();

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache             = false;
                cacheContext.IgnoreFailedSources = false;

                // Pre-loaded request provider containing the graph file
                var providers = new List <IPreLoadedRestoreRequestProvider>
                {
                    new DependencyGraphSpecRequestProvider(providerCache, dgSpec)
                };

                var restoreContext = new RestoreArgs()
                {
                    CacheContext              = cacheContext,
                    LockFileVersion           = LockFileFormat.Version,
                    Log                       = packageReferenceArgs.Logger,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    GlobalPackagesFolder      = packageReferenceArgs.PackageDirectory,
                    PreLoadedRequestProviders = providers,
                    Sources                   = packageReferenceArgs.Sources?.ToList()
                };

                // Generate Restore Requests. There will always be 1 request here since we are restoring for 1 project.
                var restoreRequests = await RestoreRunner.GetRequests(restoreContext);

                //Setup the Credential Service
                DefaultCredentialServiceUtility.SetupDefaultCredentialService(restoreContext.Log, !packageReferenceArgs.Interactive);

                // Run restore without commit. This will always return 1 Result pair since we are restoring for 1 request.
                var restoreResult = await RestoreRunner.RunWithoutCommit(restoreRequests, restoreContext);

                return(restoreResult.Single());
            }
        }
Beispiel #6
0
        public static async Task <(RestoreRequest, RestoreResult)> Restore(ILogger logger, string packageName, VersionRange versionRange)
        {
            var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null);
            var packageSourceProvider = new PackageSourceProvider(settings);
            var installPath           = SettingsUtility.GetGlobalPackagesFolder(settings);
            var assemblies            = new List <string>();

            var projectPath = Path.Combine("XenkoNugetResolver.json");
            var spec        = new PackageSpec()
            {
                Name         = Path.GetFileNameWithoutExtension(projectPath), // make sure this package never collides with a dependency
                FilePath     = projectPath,
                Dependencies = new List <LibraryDependency>()
                {
                    new LibraryDependency
                    {
                        LibraryRange = new LibraryRange(packageName, versionRange, LibraryDependencyTarget.Package),
                    }
                },
                TargetFrameworks =
                {
                    new TargetFrameworkInformation
                    {
                        FrameworkName = NuGetFramework.Parse("net48"),
                    }
                },
                RestoreMetadata = new ProjectRestoreMetadata
                {
                    ProjectPath              = projectPath,
                    ProjectName              = Path.GetFileNameWithoutExtension(projectPath),
                    ProjectStyle             = ProjectStyle.PackageReference,
                    ProjectUniqueName        = projectPath,
                    OutputPath               = Path.Combine(Path.GetTempPath(), $"XenkoNugetResolver-{packageName}-{versionRange.MinVersion.ToString()}"),
                    OriginalTargetFrameworks = new[] { "net48" },
                    ConfigFilePaths          = settings.GetConfigFilePaths(),
                    PackagesPath             = SettingsUtility.GetGlobalPackagesFolder(settings),
                    Sources         = SettingsUtility.GetEnabledSources(settings).ToList(),
                    FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToList()
                },
            };

            // remove all remote sources, so we don't have to worry about connectivity issues
            // we are only restoring local dev packages anyway
            for (int i = 0; i < spec.RestoreMetadata.Sources.Count; i++)
            {
                var s = spec.RestoreMetadata.Sources[i];
                if (s.IsLocal == false)
                {
                    spec.RestoreMetadata.Sources.RemoveAt(i);
                    i--;
                }
            }

            using (var context = new SourceCacheContext())
            {
                context.IgnoreFailedSources = true;

                var dependencyGraphSpec = new DependencyGraphSpec();

                dependencyGraphSpec.AddProject(spec);

                dependencyGraphSpec.AddRestore(spec.RestoreMetadata.ProjectUniqueName);

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

                var restoreArgs = new RestoreArgs
                {
                    AllowNoOp             = true,
                    CacheContext          = context,
                    CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(settings)),
                    Log = logger,
                };

                // Create requests from the arguments
                var requests = requestProvider.CreateRequests(restoreArgs).Result;

                // Restore the packages
                for (int tryCount = 0; tryCount < 2; ++tryCount)
                {
                    try
                    {
                        var results = await RestoreRunner.RunWithoutCommit(requests, restoreArgs);

                        // Commit results so that noop cache works next time
                        foreach (var result in results)
                        {
                            await result.Result.CommitAsync(logger, CancellationToken.None);
                        }
                        var mainResult = results.First();
                        return(mainResult.SummaryRequest.Request, mainResult.Result);
                    }
                    catch (Exception e) when(e is UnauthorizedAccessException || e is IOException)
                    {
                        // If we have an unauthorized access exception, it means assemblies are locked by running Xenko process
                        // During first try, kill some known harmless processes, and try again
                        if (tryCount == 1)
                        {
                            throw;
                        }

                        foreach (var process in new[] { "Xenko.ConnectionRouter" }.SelectMany(Process.GetProcessesByName))
                        {
                            try
                            {
                                if (process.Id != Process.GetCurrentProcess().Id)
                                {
                                    process.Kill();
                                    process.WaitForExit();
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }

                throw new InvalidOperationException("Unreachable code");
            }
        }
Beispiel #7
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);
        }
Beispiel #8
0
        public static (RestoreRequest, RestoreResult) Restore(ILogger logger, NuGetFramework nugetFramework, string runtimeIdentifier, string packageName, VersionRange versionRange, string settingsRoot = null)
        {
            var settings = NuGet.Configuration.Settings.LoadDefaultSettings(settingsRoot);

            var assemblies = new List <string>();

            var projectPath = Path.Combine("StrideNugetResolver.json");
            var spec        = new PackageSpec()
            {
                // Make sure this package never collides with a dependency
                Name         = Path.GetFileNameWithoutExtension(projectPath),
                FilePath     = projectPath,
                Dependencies = new List <LibraryDependency>()
                {
                    new LibraryDependency
                    {
                        LibraryRange = new LibraryRange(packageName, versionRange, LibraryDependencyTarget.Package),
                    }
                },
                TargetFrameworks =
                {
                    new TargetFrameworkInformation
                    {
                        FrameworkName = nugetFramework,
                    }
                },
                RestoreMetadata = new ProjectRestoreMetadata
                {
                    ProjectPath              = projectPath,
                    ProjectName              = Path.GetFileNameWithoutExtension(projectPath),
                    ProjectStyle             = ProjectStyle.PackageReference,
                    ProjectUniqueName        = projectPath,
                    OutputPath               = Path.Combine(Path.GetTempPath(), $"StrideNugetResolver-{packageName}-{versionRange.MinVersion.ToString()}-{nugetFramework.GetShortFolderName()}-{runtimeIdentifier}"),
                    OriginalTargetFrameworks = new[] { nugetFramework.GetShortFolderName() },
                    ConfigFilePaths          = settings.GetConfigFilePaths(),
                    PackagesPath             = SettingsUtility.GetGlobalPackagesFolder(settings),
                    Sources         = SettingsUtility.GetEnabledSources(settings).ToList(),
                    FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToList()
                },
                RuntimeGraph = new RuntimeGraph(new[] { new RuntimeDescription(runtimeIdentifier) })
            };

            using (var context = new SourceCacheContext())
            {
                context.IgnoreFailedSources = true;

                var dependencyGraphSpec = new DependencyGraphSpec();
                dependencyGraphSpec.AddProject(spec);
                dependencyGraphSpec.AddRestore(spec.RestoreMetadata.ProjectUniqueName);

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

                var restoreArgs = new RestoreArgs
                {
                    AllowNoOp             = true,
                    CacheContext          = context,
                    CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(settings)),
                    Log = logger,
                };

                // Create requests from the arguments
                var requests = requestProvider.CreateRequests(restoreArgs).Result;

                // Restore the packages
                for (int tryCount = 0; tryCount < 2; ++tryCount)
                {
                    try
                    {
                        var results = RestoreRunner.RunWithoutCommit(requests, restoreArgs).Result;

                        // Commit results so that noop cache works next time
                        foreach (var result in results)
                        {
                            result.Result.CommitAsync(logger, CancellationToken.None).Wait();
                        }
                        var mainResult = results.First();
                        return(mainResult.SummaryRequest.Request, mainResult.Result);
                    }
                    catch (Exception e) when(e is UnauthorizedAccessException || e is IOException || ((e is AggregateException ae) && ae.InnerExceptions.Any(e2 => e2 is UnauthorizedAccessException || e2 is IOException)))
                    {
                        // If we have an unauthorized access exception, it means assemblies are locked by running Stride process
                        // During first try, kill some known harmless processes, and try again
                        if (tryCount == 1)
                        {
                            throw;
                        }

                        foreach (var process in new[] { "Stride.ConnectionRouter" }.SelectMany(Process.GetProcessesByName))
                        {
                            try
                            {
                                if (process.Id != Process.GetCurrentProcess().Id)
                                {
                                    process.Kill();
                                    process.WaitForExit();
                                }
                            }
                            catch { }
                        }
                    }
                }

                Debug.Fail("Unreachable code");
                return(default);