Example #1
0
        /// <summary>
        /// Find available packages from source with Id matching <paramref name="packageId"/>.
        /// </summary>
        /// <param name="packageId">Id of package we are looking for.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A list of packages matching <paramref name="packageId"/> or an empty list if none is found.</returns>
        public async Task <IEnumerable <NugetServerPackage> > FindSourcePackagesById(string packageId, CancellationToken cancellationToken)
        {
            var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();
            var res          = new List <NugetServerPackage>();

            await FindSourcePacakgesByIdHelper(packageId, res, repositories, cancellationToken);

            return(res);
        }
Example #2
0
        /// <summary>
        /// Find available packages from source ith Ids matching <paramref name="packageIds"/>.
        /// </summary>
        /// <param name="packageIds">List of package Ids we are looking for.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A list of packages matching <paramref name="packageIds"/> or an empty list if none is found.</returns>
        public async Task <IEnumerable <NugetServerPackage> > FindSourcePackages(IReadOnlyCollection <string> packageIds, CancellationToken cancellationToken)
        {
            var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();
            var res          = new List <NugetServerPackage>();

            foreach (var packageId in packageIds)
            {
                await FindSourcePackagesByIdHelper(packageId, res, repositories, cancellationToken);
            }
            return(res);
        }
        public PackageSourceMoniker(string sourceName, IEnumerable <PackageSourceContextInfo> packageSources)
        {
            SourceName = sourceName;

            if (packageSources == null)
            {
                throw new ArgumentNullException(nameof(packageSources));
            }
            if (!packageSources.Any())
            {
                throw new ArgumentException("List of sources cannot be empty", nameof(packageSources));
            }

            PackageSources     = packageSources.ToArray();
            PackageSourceNames = PackageSources.Select(s => s.Name).ToList();

            _stringRepresentation = $"{SourceName}: [{string.Join("; ", PackageSourceNames)}]";
            _tooltip = PackageSources.Count() == 1
                ? GetTooltip(PackageSources.First())
                : string.Join("; ", PackageSourceNames);
        }
Example #4
0
        /// <summary>
        /// Returns updates for packages from the repository
        /// </summary>
        /// <param name="packageName">Package to look for updates</param>
        /// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param>
        /// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns></returns>
        public async Task <IEnumerable <NugetPackage> > GetUpdates(PackageName packageName, bool includePrerelease, bool includeAllVersions, CancellationToken cancellationToken)
        {
            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrerelease,
                true,
                includeAllVersions ? VersionConstraints.None : VersionConstraints.ExactMajor | VersionConstraints.ExactMinor);

            var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();

            var res = new List <NugetPackage>();

            using (var context = new SourceCacheContext {
                MaxAge = DateTimeOffset.UtcNow
            })
            {
                foreach (var repo in repositories)
                {
                    try
                    {
                        var metadataResource = await repo.GetResourceAsync <PackageMetadataResource>(cancellationToken);

                        var metadataList = await metadataResource.GetMetadataAsync(packageName.Id, includePrerelease, includeAllVersions, context, NativeLogger, cancellationToken);

                        foreach (var metadata in metadataList)
                        {
                            if (metadata.IsListed)
                            {
                                res.Add(new NugetServerPackage(metadata, repo.PackageSource.Source));
                            }
                        }
                    }
                    catch (FatalProtocolException)
                    {
                        // Ignore 404/403 etc... (invalid sources)
                    }
                }
            }
            return(res);
        }
Example #5
0
        /// <summary>
        /// Look for available packages from source containing <paramref name="searchTerm"/> in either the Id or description of the package.
        /// </summary>
        /// <param name="searchTerm">Term used for search.</param>
        /// <param name="allowPrereleaseVersions">Are we looking in pre-release versions too?</param>
        /// <returns>A list of packages matching <paramref name="searchTerm"/>.</returns>
        public async Task <IQueryable <NugetPackage> > SourceSearch(string searchTerm, bool allowPrereleaseVersions)
        {
            var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();
            var res          = new List <NugetPackage>();

            foreach (var repo in repositories)
            {
                try
                {
                    var searchResource = await repo.GetResourceAsync <PackageSearchResource>(CancellationToken.None);

                    if (searchResource != null)
                    {
                        var searchResults = await searchResource.SearchAsync(searchTerm, new SearchFilter(includePrerelease : false), 0, 0, NativeLogger, CancellationToken.None);

                        if (searchResults != null)
                        {
                            var packages = searchResults.ToArray();

                            foreach (var package in packages)
                            {
                                if (package.IsListed)
                                {
                                    res.Add(new NugetServerPackage(package, repo.PackageSource.Source));
                                }
                            }
                        }
                    }
                }
                catch (FatalProtocolException)
                {
                    // Ignore 404/403 etc... (invalid sources)
                }
            }
            return(res.AsQueryable());
        }
Example #6
0
        /// <summary>
        /// Fetch, if not already downloaded, and install the package represented by
        /// (<paramref name="packageId"/>, <paramref name="version"/>).
        /// </summary>
        /// <remarks>It is safe to call it concurrently be cause we operations are done using the FileLock.</remarks>
        /// <param name="packageId">Name of package to install.</param>
        /// <param name="version">Version of package to install.</param>
        public async Task <NugetLocalPackage> InstallPackage(string packageId, PackageVersion version, IEnumerable <string> targetFrameworks, ProgressReport progress)
        {
            using (GetLocalRepositoryLock())
            {
                currentProgressReport = progress;
                try
                {
                    var identity = new PackageIdentity(packageId, version.ToNuGetVersion());

                    var resolutionContext = new ResolutionContext(
                        DependencyBehavior.Lowest,
                        true,
                        true,
                        VersionConstraints.None);

                    var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();

                    var projectContext = new EmptyNuGetProjectContext()
                    {
                        ActionType = NuGetActionType.Install,
                        PackageExtractionContext = new PackageExtractionContext(PackageSaveMode.Defaultv3, XmlDocFileSaveMode.Skip, null, NativeLogger),
                    };

                    ActivityCorrelationId.StartNew();

                    {
                        var installPath = SettingsUtility.GetGlobalPackagesFolder(settings);

                        // In case it's a package without any TFM (i.e. Visual Studio plugin), we still need to specify one
                        if (!targetFrameworks.Any())
                        {
                            targetFrameworks = new string[] { "net6.0" }
                        }
                        ;

                        // Old version expects to be installed in GamePackages
                        if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0) && oldRootDirectory != null)
                        {
                            installPath = oldRootDirectory;
                        }

                        var projectPath = Path.Combine("StrideLauncher.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(packageId, new VersionRange(version.ToNuGetVersion()), LibraryDependencyTarget.Package),
                                }
                            },
                            RestoreMetadata = new ProjectRestoreMetadata
                            {
                                ProjectPath              = projectPath,
                                ProjectName              = Path.GetFileNameWithoutExtension(projectPath),
                                ProjectStyle             = ProjectStyle.PackageReference,
                                ProjectUniqueName        = projectPath,
                                OutputPath               = Path.Combine(Path.GetTempPath(), $"StrideLauncher-{packageId}-{version.ToString()}"),
                                OriginalTargetFrameworks = targetFrameworks.ToList(),
                                ConfigFilePaths          = settings.GetConfigFilePaths(),
                                PackagesPath             = installPath,
                                Sources         = SettingsUtility.GetEnabledSources(settings).ToList(),
                                FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToList()
                            },
                        };
                        foreach (var targetFramework in targetFrameworks)
                        {
                            spec.TargetFrameworks.Add(new TargetFrameworkInformation {
                                FrameworkName = NuGetFramework.Parse(targetFramework)
                            });
                        }

                        using (var context = new SourceCacheContext {
                            MaxAge = DateTimeOffset.UtcNow
                        })
                        {
                            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 = NativeLogger,
                            };

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

                            foreach (var request in requests)
                            {
                                // Limit concurrency to avoid timeout
                                request.Request.MaxDegreeOfConcurrency = 4;

                                var command = new RestoreCommand(request.Request);

                                // Act
                                var result = await command.ExecuteAsync();

                                if (!result.Success)
                                {
                                    throw new InvalidOperationException($"Could not restore package {packageId}");
                                }
                                foreach (var install in result.RestoreGraphs.Last().Install)
                                {
                                    var package = result.LockFile.Libraries.FirstOrDefault(x => x.Name == install.Library.Name && x.Version == install.Library.Version);
                                    if (package != null)
                                    {
                                        var packagePath = Path.Combine(installPath, package.Path);
                                        OnPackageInstalled(this, new PackageOperationEventArgs(new PackageName(install.Library.Name, install.Library.Version.ToPackageVersion()), packagePath));
                                    }
                                }
                            }
                        }

                        if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0))
                        {
                            UpdateTargetsHelper();
                        }
                    }

                    // Load the recently installed package
                    var installedPackages = GetPackagesInstalled(new[] { packageId });
                    return(installedPackages.FirstOrDefault(p => p.Version == version));
                }
                finally
                {
                    currentProgressReport = null;
                }
            }
        }
Example #7
0
        private void OnPackageSourcesChanged()
        {
            EditablePackageSources = new FastObservableCollection <EditablePackageSource>(PackageSources.Select(x =>
                                                                                                                new EditablePackageSource
            {
                IsEnabled = x.IsEnabled,
                Name      = x.Name,
                Source    = x.Source
            }));

            VerifyAll();
        }
Example #8
0
        private void OnPackageSourcesChanged()
        {
            EditablePackageSources = new FastObservableCollection <EditablePackageSource>(PackageSources.Select(x =>
                                                                                                                new EditablePackageSource
            {
                IsEnabled = x.IsEnabled,
                Name      = x.Name,
                Source    = x.Source
            }));

            if (_ignoreNextPackageUpdate)
            {
                return;
            }

            VerifyAll();
        }
Example #9
0
        /// <summary>
        /// Fetch, if not already downloaded, and install the package represented by
        /// (<paramref name="packageId"/>, <paramref name="version"/>).
        /// </summary>
        /// <remarks>It is safe to call it concurrently be cause we operations are done using the FileLock.</remarks>
        /// <param name="packageId">Name of package to install.</param>
        /// <param name="version">Version of package to install.</param>
        public async Task <NugetLocalPackage> InstallPackage(string packageId, PackageVersion version, ProgressReport progress)
        {
            using (GetLocalRepositoryLock())
            {
                currentProgressReport = progress;
                try
                {
                    var identity = new PackageIdentity(packageId, version.ToNuGetVersion());

                    var resolutionContext = new ResolutionContext(
                        DependencyBehavior.Lowest,
                        true,
                        true,
                        VersionConstraints.None);

                    var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();

                    var projectContext = new EmptyNuGetProjectContext()
                    {
                        ActionType = NuGetActionType.Install,
                        PackageExtractionContext = new PackageExtractionContext(PackageSaveMode.Defaultv3, XmlDocFileSaveMode.Skip, null, NativeLogger),
                    };

                    ActivityCorrelationId.StartNew();

                    {
                        var installPath = SettingsUtility.GetGlobalPackagesFolder(settings);

                        // Old version expects to be installed in GamePackages
                        if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0) && oldRootDirectory != null)
                        {
                            installPath = oldRootDirectory;
                        }

                        var specPath = Path.Combine("TestProject", "project.json");
                        var spec     = new PackageSpec()
                        {
                            Name         = "TestProject", // make sure this package never collides with a dependency
                            FilePath     = specPath,
                            Dependencies = new List <LibraryDependency>()
                            {
                                new LibraryDependency
                                {
                                    LibraryRange = new LibraryRange(packageId, new VersionRange(version.ToNuGetVersion()), LibraryDependencyTarget.Package),
                                }
                            },
                            TargetFrameworks =
                            {
                                new TargetFrameworkInformation
                                {
                                    FrameworkName = NuGetFramework.Parse("net472"),
                                }
                            },
                        };

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

                            var provider = RestoreCommandProviders.Create(installPath, new List <string>(), sourceRepositoryProvider.GetRepositories(), context, new LocalPackageFileCache(), NativeLogger);
                            var request  = new RestoreRequest(spec, provider, context, null, NativeLogger)
                            {
                                //RequestedRuntimes = { "win7-d3d11" },
                                ProjectStyle = ProjectStyle.DotnetCliTool,
                            };

                            var command = new RestoreCommand(request);

                            // Act
                            var result = await command.ExecuteAsync();

                            if (!result.Success)
                            {
                                throw new InvalidOperationException($"Could not restore package {packageId}");
                            }
                            foreach (var install in result.RestoreGraphs.Last().Install)
                            {
                                var package = result.LockFile.Libraries.FirstOrDefault(x => x.Name == install.Library.Name && x.Version == install.Library.Version);
                                if (package != null)
                                {
                                    var packagePath = Path.Combine(installPath, package.Path);
                                    OnPackageInstalled(this, new PackageOperationEventArgs(new PackageName(install.Library.Name, install.Library.Version.ToPackageVersion()), packagePath));
                                }
                            }
                        }

                        if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0))
                        {
                            UpdateTargetsHelper();
                        }
                    }

                    // Load the recently installed package
                    var installedPackages = GetPackagesInstalled(new[] { packageId });
                    return(installedPackages.FirstOrDefault(p => p.Version == version));
                }
                finally
                {
                    currentProgressReport = null;
                }
            }
        }
Example #10
0
        /// <summary>
        /// Fetch, if not already downloaded, and install the package represented by
        /// (<paramref name="packageId"/>, <paramref name="version"/>).
        /// </summary>
        /// <remarks>It is safe to call it concurrently be cause we operations are done using the FileLock.</remarks>
        /// <param name="packageId">Name of package to install.</param>
        /// <param name="version">Version of package to install.</param>
        public async Task <NugetLocalPackage> InstallPackage(string packageId, PackageVersion version, ProgressReport progress)
        {
            // Xenko 2.x still installs in GamePackages
            var currentManager = IsPackageV2(packageId, version) ? managerV2 : manager;

            using (GetLocalRepositoryLock())
            {
                currentProgressReport = progress;
                try
                {
                    var identity = new PackageIdentity(packageId, version.ToNuGetVersion());

                    var resolutionContext = new ResolutionContext(
                        DependencyBehavior.Lowest,
                        true,
                        true,
                        VersionConstraints.None);

                    var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();

                    var projectContext = new EmptyNuGetProjectContext()
                    {
                        ActionType = NuGetActionType.Install,
                        PackageExtractionContext = new PackageExtractionContext(NativeLogger),
                    };

                    ActivityCorrelationId.StartNew();

                    {
                        // Equivalent to:
                        //   await manager.InstallPackageAsync(manager.PackagesFolderNuGetProject,
                        //       identity, resolutionContext, projectContext, repositories,
                        //       Array.Empty<SourceRepository>(),  // This is a list of secondary source respositories, probably empty
                        //       CancellationToken.None);
                        using (var sourceCacheContext = new SourceCacheContext())
                        {
                            var nuGetProject        = currentManager.PackagesFolderNuGetProject;
                            var packageIdentity     = identity;
                            var nuGetProjectContext = projectContext;
                            var primarySources      = repositories;
                            var secondarySources    = Array.Empty <SourceRepository>();
                            var token           = CancellationToken.None;
                            var downloadContext = new PackageDownloadContext(sourceCacheContext);

                            // Step-1 : Call PreviewInstallPackageAsync to get all the nuGetProjectActions
                            var nuGetProjectActions = await currentManager.PreviewInstallPackageAsync(nuGetProject, packageIdentity, resolutionContext,
                                                                                                      nuGetProjectContext, primarySources, secondarySources, token);

                            // Notify that installations started.
                            foreach (var operation in nuGetProjectActions)
                            {
                                if (operation.NuGetProjectActionType == NuGetProjectActionType.Install)
                                {
                                    var installPath = GetInstalledPath(operation.PackageIdentity.Id, operation.PackageIdentity.Version.ToPackageVersion());
                                    OnPackageInstalling(this, new PackageOperationEventArgs(new PackageName(operation.PackageIdentity.Id, operation.PackageIdentity.Version.ToPackageVersion()), installPath));
                                }
                            }

                            NuGetPackageManager.SetDirectInstall(packageIdentity, nuGetProjectContext);

                            // Step-2 : Execute all the nuGetProjectActions
                            if (IsPackageV2(packageId, version))
                            {
                                await currentManager.ExecuteNuGetProjectActionsAsync(
                                    nuGetProject,
                                    nuGetProjectActions,
                                    nuGetProjectContext,
                                    downloadContext,
                                    token);
                            }
                            else
                            {
                                // Download and install package in the global cache (can't use NuGetPackageManager anymore since it is designed for V2)
                                foreach (var operation in nuGetProjectActions)
                                {
                                    if (operation.NuGetProjectActionType == NuGetProjectActionType.Install)
                                    {
                                        using (var downloadResult = await PackageDownloader.GetDownloadResourceResultAsync(primarySources, packageIdentity, downloadContext, InstallPath, NativeLogger, token))
                                        {
                                            if (downloadResult.Status != DownloadResourceResultStatus.Available)
                                            {
                                                throw new InvalidOperationException($"Could not download package {packageIdentity}");
                                            }

                                            using (var installResult = await GlobalPackagesFolderUtility.AddPackageAsync(packageIdentity, downloadResult.PackageStream, InstallPath, NativeLogger, token))
                                            {
                                                if (installResult.Status != DownloadResourceResultStatus.Available)
                                                {
                                                    throw new InvalidOperationException($"Could not install package {packageIdentity}");
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            NuGetPackageManager.ClearDirectInstall(nuGetProjectContext);

                            // Notify that installations completed.
                            foreach (var operation in nuGetProjectActions)
                            {
                                if (operation.NuGetProjectActionType == NuGetProjectActionType.Install)
                                {
                                    var installPath = GetInstalledPath(operation.PackageIdentity.Id, operation.PackageIdentity.Version.ToPackageVersion());
                                    OnPackageInstalled(this, new PackageOperationEventArgs(new PackageName(operation.PackageIdentity.Id, operation.PackageIdentity.Version.ToPackageVersion()), installPath));
                                }
                            }
                        }
                    }

                    // Load the recently installed package
                    var installedPackages = GetPackagesInstalled(new[] { packageId });
                    return(installedPackages.FirstOrDefault(p => p.Version == version));
                }
                finally
                {
                    currentProgressReport = null;
                }
            }
        }