public static SimpleTestProjectContext CreateProject(string projectName,
                                                             SimpleTestPathContext pathContext,
                                                             string projectFrameworks)
        {
            var settings = Settings.LoadDefaultSettings(Path.GetDirectoryName(pathContext.NuGetConfig), Path.GetFileName(pathContext.NuGetConfig), null);
            var project  = SimpleTestProjectContext.CreateNETCoreWithSDK(
                projectName: projectName,
                solutionRoot: pathContext.SolutionRoot,
                isToolingVersion15: true,
                frameworks: MSBuildStringUtility.Split(projectFrameworks));

            project.FallbackFolders      = (IList <string>)SettingsUtility.GetFallbackPackageFolders(settings);
            project.GlobalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
            var packageSourceProvider = new PackageSourceProvider(settings);

            project.Sources = packageSourceProvider.LoadPackageSources();

            project.Save();
            return(project);
        }
Exemple #2
0
        public NuGetViewModel()
        {
            _settings = Settings.LoadDefaultSettings(
                Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
                configFileName: null,
                machineWideSettings: new CommandLineMachineWideSettings());

            _sourceProvider = new PackageSourceProvider(_settings);

            GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(_settings);

            _packageSources = GetPackageSources();

            _sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(_sourceProvider);

            _initializationTask = new Lazy <Task>(Initialize);

            InstallPackageCommand = new DelegateCommand <IPackage>(InstallPackage);

            IsEnabled = true;
        }
        /// <returns>a global packages folder, or null in scenarios where it cannot be computed.</returns>
        public static string GetEffectiveGlobalPackagesFolderOrNull(string solutionDirectory, ISettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            var globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(settings);

            if (Path.IsPathRooted(globalPackagesFolder))
            {
                return(globalPackagesFolder);
            }

            if (string.IsNullOrEmpty(solutionDirectory) || !Path.IsPathRooted(solutionDirectory))
            {
                return(null);
            }

            return(Path.GetFullPath(Path.Combine(solutionDirectory, globalPackagesFolder)));
        }
Exemple #4
0
        protected IReadOnlyCollection <Configuration.PackageSource> GetPackageSources(Configuration.ISettings settings)
        {
            var availableSources = SourceProvider.LoadPackageSources().Where(source => source.IsEnabled);
            var packageSources   = new List <Configuration.PackageSource>();

            if (!NoCache)
            {
                // Add the v2 machine cache
                if (!string.IsNullOrEmpty(MachineCache.Default?.Source))
                {
                    packageSources.Add(new V2PackageSource(MachineCache.Default.Source, () => MachineCache.Default));
                }

                // Add the v3 global packages folder
                var globalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(settings);

                if (!string.IsNullOrEmpty(globalPackageFolder) && Directory.Exists(globalPackageFolder))
                {
                    packageSources.Add(new V2PackageSource(globalPackageFolder,
                                                           () => new LocalPackageRepository(globalPackageFolder)));
                }
            }

            foreach (var source in Source)
            {
                packageSources.Add(Common.PackageSourceProviderExtensions.ResolveSource(availableSources, source));
            }

            if (Source.Count == 0)
            {
                packageSources.AddRange(availableSources);
            }

            foreach (var source in FallbackSource)
            {
                packageSources.Add(Common.PackageSourceProviderExtensions.ResolveSource(packageSources, source));
            }

            return(packageSources);
        }
        /// <summary>
        /// Initialize a new instance of <see cref="NugetStore"/>.
        /// </summary>
        /// <param name="oldRootDirectory">The location of the Nuget store.</param>
        public NugetStore(string oldRootDirectory)
        {
            // Workaround for https://github.com/NuGet/Home/issues/8120
            //  set timeout to something much higher than 100 sec
            var defaultRequestTimeoutField = typeof(HttpSourceRequest).GetField(nameof(HttpSourceRequest.DefaultRequestTimeout), BindingFlags.Static | BindingFlags.Public);

            if (defaultRequestTimeoutField != null)
            {
                defaultRequestTimeoutField.SetValue(null, TimeSpan.FromMinutes(60));
            }

            // Used only for versions before 3.0
            this.oldRootDirectory = oldRootDirectory;

            settings = NuGet.Configuration.Settings.LoadDefaultSettings(null);

            // Remove obsolete sources
            RemoveDeletedSources(settings, "Xenko Dev");
            // Note the space: we want to keep "Stride Dev" but not "Stride Dev {PATH}\bin\packages" anymore
            RemoveSources(settings, "Stride Dev ");
            // Add Stride package store (still used for Xenko up to 3.0)
            CheckPackageSource("Stride", DefaultPackageSource);
            settings.SaveToDisk();

            InstallPath = SettingsUtility.GetGlobalPackagesFolder(settings);

            var pathContext = NuGetPathContext.Create(settings);

            InstalledPathResolver = new FallbackPackagePathResolver(pathContext.UserPackageFolder, oldRootDirectory != null ? pathContext.FallbackPackageFolders.Concat(new[] { oldRootDirectory }) : pathContext.FallbackPackageFolders);
            var packageSourceProvider = new PackageSourceProvider(settings);

            var availableSources = packageSourceProvider.LoadPackageSources().Where(source => source.IsEnabled);
            var packageSources   = new List <PackageSource>();

            packageSources.AddRange(availableSources);
            PackageSources = packageSources;

            // Setup source provider as a V3 only.
            sourceRepositoryProvider = new NugetSourceRepositoryProvider(packageSourceProvider, this);
        }
        public void BuildAssetsUtils_ReplaceWithUserProfileMacro()
        {
            // Arrange
            using (var randomProjectDirectory = TestDirectory.Create())
            {
                var globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(NullSettings.Instance);

                if (!string.IsNullOrEmpty(globalPackagesFolder))
                {
                    // Act
                    var xml = BuildAssetsUtils.GenerateEmptyImportsFile();

                    BuildAssetsUtils.AddNuGetProperties(
                        xml,
                        new[] { globalPackagesFolder },
                        globalPackagesFolder,
                        ProjectStyle.PackageReference,
                        assetsFilePath: string.Empty,
                        success: true);

                    // Assert
                    var ns       = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");
                    var elements = xml.Root.Descendants(ns + "NuGetPackageRoot");
                    Assert.Single(elements);

                    var    element  = elements.Single();
                    string expected = null;

                    if (RuntimeEnvironmentHelper.IsWindows)
                    {
                        expected = Path.Combine(@"$(UserProfile)", ".nuget", "packages") + Path.DirectorySeparatorChar;
                    }
                    else
                    {
                        expected = Path.Combine(Environment.GetEnvironmentVariable("HOME"), ".nuget", "packages") + Path.DirectorySeparatorChar;
                    }
                    Assert.Equal(expected, element.Value);
                }
            }
        }
Exemple #7
0
        private void Generate()
        {
            Console.WriteLine("Generating early bound objects...");

            var authType         = _authSettings.AuthType;
            var url              = _authSettings.Url;
            var clientId         = _authSettings.ClientId;
            var clientSecret     = _authSettings.ClientSecret;
            var connectionString = $"AuthType={authType};url={url};ClientId={clientId};ClientSecret={clientSecret}";

            var          settings = Settings.LoadDefaultSettings(null);
            var          nugetPackagesDirectory   = SettingsUtility.GetGlobalPackagesFolder(settings);
            const string toolsVersion             = "9.1.0.49";
            var          solutionPackagerFilePath =
                $@"{nugetPackagesDirectory}Microsoft.CrmSdk.CoreTools/{toolsVersion}/content/bin/coretools/CrmSvcUtil.exe";
            var connectionParameter = $@"/connectionstring:{connectionString}";

            var process = new Process
            {
                StartInfo =
                {
                    FileName               = solutionPackagerFilePath,
                    Arguments              = $@"{connectionParameter} /out:Generated.cs /namespace:LinkedIn.Internal.Crm.Common.Generated",
                    CreateNoWindow         = true,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true
                }
            };

            Console.WriteLine("Generating...");
            process.OutputDataReceived += (sender, data) => Console.WriteLine(data.Data);
            process.ErrorDataReceived  += (sender, data) => Console.WriteLine(data.Data);
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit();
            process.Kill();
        }
        private void UnPackSolution()
        {
            Console.WriteLine("Extracting solution...");
            var settings = Settings.LoadDefaultSettings(null);
            var nugetPackagesDirectory = SettingsUtility.GetGlobalPackagesFolder(settings);

            var toolsVersion             = $@"{_solutionSettings.ToolsVersion}";
            var solutionPackagerFilePath =
                $@"{nugetPackagesDirectory}Microsoft.CrmSdk.CoreTools/{toolsVersion}/content/bin/coretools/SolutionPackager.exe";
            var solutionPackageType = $@"/packagetype:{_solutionSettings.SolutionPackageType}";
            var solutionPackageMap  = $@"/map:{_solutionSettings.SolutionPackageMapFilePath}";
            var solutionExtractPath = $@"/folder:{_solutionSettings.SolutionExtractPath}";
            var zip        = $@"/zipfile:{_solutionSettings.SolutionExportDirectory}{_solutionSettings.SolutionName}.zip";
            var errorLevel = $@"/errorlevel:{_solutionSettings.ErrorLevel}";
            var logFile    = $@"/l:{_solutionSettings.SolutionExportDirectory}SolutionPackager.log";

            var process = new Process
            {
                StartInfo =
                {
                    FileName  = solutionPackagerFilePath,
                    Arguments =
                        $@"/action:Extract {solutionPackageType} {solutionPackageMap} {zip} {solutionExtractPath} {errorLevel} {logFile}",
                    CreateNoWindow         = true,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    WorkingDirectory       = _solutionSettings.CdsSolutionProjectPath
                }
            };

            process.OutputDataReceived += (sender, data) => Console.WriteLine(data.Data);
            process.ErrorDataReceived  += (sender, data) => Console.WriteLine(data.Data);
            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            process.WaitForExit(1000 * 15);
            process.Kill();
        }
Exemple #9
0
        public async Task <(PackageReaderBase package, string installPath)> DownloadPackage(
            SourcePackageDependencyInfo packageToInstall)
        {
            var packagePathResolver      = new PackagePathResolver(Path.GetFullPath("packages"));
            var packageExtractionContext =
                new PackageExtractionContext(
                    PackageSaveMode.Defaultv3,
                    XmlDocFileSaveMode.None,
                    ClientPolicyContext.GetClientPolicy(_settings, _logger),
                    _logger);

            var installedPath = packagePathResolver.GetInstalledPath(packageToInstall);

            if (installedPath != null)
            {
                return(new PackageFolderReader(installedPath), installedPath);
            }

            var downloadResource =
                await packageToInstall.Source.GetResourceAsync <DownloadResource>(CancellationToken.None);

            var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                packageToInstall,
                new PackageDownloadContext(_sourceCacheContext),
                SettingsUtility.GetGlobalPackagesFolder(_settings),
                _logger,
                CancellationToken.None);

            await PackageExtractor.ExtractPackageAsync(
                downloadResult.PackageSource,
                downloadResult.PackageStream,
                packagePathResolver,
                packageExtractionContext,
                CancellationToken.None);

            installedPath = packagePathResolver.GetInstalledPath(packageToInstall);

            return(downloadResult.PackageReader, installedPath);
        }
Exemple #10
0
        public PackageLoader(UpgradeOptions options, ILogger <PackageLoader> logger)
        {
            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (options.ProjectPath is null)
            {
                throw new ArgumentException("Project path must be set in UpgradeOptions", nameof(options));
            }

            _logger                = logger ?? throw new ArgumentNullException(nameof(logger));
            _nugetLogger           = new NuGetLogger(logger);
            _cache                 = new SourceCacheContext();
            _packageSources        = GetPackageSources(Path.GetDirectoryName(options.ProjectPath));
            _sourceRepositoryCache = new Dictionary <PackageSource, SourceRepository>();

            var settings = Settings.LoadDefaultSettings(null);

            _cachePath = SettingsUtility.GetGlobalPackagesFolder(settings);
        }
Exemple #11
0
        public NuGetViewModel()
        {
            try
            {
                _settings = Settings.LoadDefaultSettings(
                    root: null,
                    configFileName: null,
                    machineWideSettings: new CommandLineMachineWideSettings());

                _sourceProvider = new PackageSourceProvider(_settings);

                GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(_settings);

                _packageSources = GetPackageSources();

                _sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(_sourceProvider);
            }
            catch (Exception e)
            {
                _initializationException = ExceptionDispatchInfo.Capture(e);
            }
        }
Exemple #12
0
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
        public NuGetViewModel()
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
        {
            try {
                var settings = Settings.LoadDefaultSettings(
                    root: null,
                    configFileName: null,
                    machineWideSettings: new XPlatMachineWideSetting());

                GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
                _configFilePaths    = settings.GetConfigFilePaths();
                _packageSources     = SettingsUtility.GetEnabledSources(settings);

                DefaultCredentialServiceUtility.SetupDefaultCredentialService(NullLogger.Instance, nonInteractive: false);

                var sourceProvider = new PackageSourceProvider(settings);
                _sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(sourceProvider);
            }
            catch (Exception e) {
                _initializationException = ExceptionDispatchInfo.Capture(e);
            }
        }
Exemple #13
0
        public NugetPackage(ILogger logger, NugetManager manager)
        {
            _manager = manager;
            _logger  = logger;
            try
            {
                ISettings settings;
                try
                {
                    settings = Settings.LoadDefaultSettings(
                        root: null,
                        configFileName: null,
                        machineWideSettings: new XPlatMachineWideSetting());
                }
                catch (NuGetConfigurationException)
                {
                    // create default settings using a non-existent config file
                    settings = new Settings(nameof(NugetPackage));
                }

                GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
                _configFilePaths    = new List <string>(); //SettingsUtility.GetConfigFilePaths(settings);
                var sources = SettingsUtility.GetEnabledSources(settings);
                _packageSources = _manager.AdditionalSources.Select(p => new PackageSource(p.source, p.name)).Concat(sources).ToList();
                DefaultCredentialServiceUtility.SetupDefaultCredentialService(NullLogger.Instance,
                                                                              nonInteractive: false);

                var sourceProvider = new PackageSourceProvider(settings);
                var providers      = new List <Lazy <INuGetResourceProvider> >();
                providers.AddRange(Repository.Provider.GetCoreV3());
                _sourceRepositories = _packageSources.Select(s => new SourceRepository(s, providers)).ToList();
            }
            catch (Exception e)
            {
                _logger?.LogError(e.Message + e.StackTrace);
                _initializationException = ExceptionDispatchInfo.Capture(e);
            }
        }
Exemple #14
0
        public async Task DownloadPackages()
        {
            var mgr = Init();

            void ClearCache(string pkgName, NuGetVersion pkgVersion)
            {
                var pkg      = new PackageIdentity(pkgName, pkgVersion);
                var localPkg = LocalFolderUtility.GetPackageV3(SettingsUtility.GetGlobalPackagesFolder(mgr.NugetSettings), pkg, mgr.Logger);

                if (localPkg != null)
                {
                    Directory.Delete(Path.GetDirectoryName(localPkg.Path), true);
                }
            }

            // Remove "Microsoft.Quantum.Chemistry" and "Microsoft.Quantum.Research" from local cache,
            // Do this on an old version, to make sure we don't try to delete a loaded assembly:
            var version = NuGetVersion.Parse("0.3.1811.2802-preview ");

            ClearCache("Microsoft.Quantum.Chemistry", version);
            ClearCache("Microsoft.Quantum.Research", version);

            var researchPkg = new PackageIdentity("Microsoft.Quantum.Research", version);
            var chemPkg     = new PackageIdentity("Microsoft.Quantum.Chemistry", version);

            using (var context = new SourceCacheContext())
            {
                var dependencies = await mgr.GetPackageDependencies(researchPkg, context);

                Assert.IsFalse(mgr.IsInstalled(researchPkg));
                Assert.IsFalse(mgr.IsInstalled(chemPkg));

                await mgr.DownloadPackages(context, dependencies);

                Assert.IsTrue(mgr.IsInstalled(researchPkg));
                Assert.IsTrue(mgr.IsInstalled(chemPkg));
            }
        }
        public static async Task Download(
            IMonoDevelopSolutionManager solutionManager,
            PackageIdentity packageIdentity,
            INuGetProjectContext context,
            CancellationToken token)
        {
            if (!IsMissing(solutionManager, packageIdentity))
            {
                return;
            }

            using (var sourceCacheContext = new SourceCacheContext()) {
                var downloadContext = new PackageDownloadContext(sourceCacheContext);

                await PackageDownloader.GetDownloadResourceResultAsync(
                    solutionManager.CreateSourceRepositoryProvider().GetRepositories(),
                    packageIdentity,
                    downloadContext,
                    SettingsUtility.GetGlobalPackagesFolder(solutionManager.Settings),
                    new LoggerAdapter (context),
                    token);
            }
        }
Exemple #16
0
        private async Task<PackageReaderBase> ExtractPackage(
            SourcePackageDependencyInfo packageInfo,
            NuGetFramework projectFramework,
            SourceCacheContext cacheContext,
            PackageExtractionContext packageExtractionContext,
            ILogger logger,
            CancellationToken token)
        {
            logger.LogInformation($"Installing package '{packageInfo.Id} {packageInfo.Version}'.");
            var downloadResource = await packageInfo.Source.GetResourceAsync<DownloadResource>(token);
            var downloadResult = await downloadResource.GetDownloadResourceResultAsync(
                packageInfo,
                new PackageDownloadContext(cacheContext),
                SettingsUtility.GetGlobalPackagesFolder(Settings),
                logger, token);

            var installPath = PathResolver.GetInstallPath(packageInfo);
            foreach (var plugin in PackageManagerPlugins)
            {
                var accepted = await plugin.OnPackageInstallingAsync(packageInfo, projectFramework, downloadResult.PackageReader, installPath);
                if (!accepted) return downloadResult.PackageReader;
            }

            await PackageExtractor.ExtractPackageAsync(
                downloadResult.PackageSource,
                downloadResult.PackageStream,
                PathResolver,
                packageExtractionContext,
                token);

            installPath = PathResolver.GetInstalledPath(packageInfo);
            foreach (var plugin in PackageManagerPlugins)
            {
                await plugin.OnPackageInstalledAsync(packageInfo, projectFramework, downloadResult.PackageReader, installPath);
            }
            return downloadResult.PackageReader;
        }
Exemple #17
0
        public void GetGlobalPackagesFolder_Default()
        {
            // Arrange
#if !IS_CORECLR
            var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
#else
            string userProfile = null;
            if (RuntimeEnvironmentHelper.IsWindows)
            {
                userProfile = Environment.GetEnvironmentVariable("UserProfile");
            }
            else
            {
                userProfile = Environment.GetEnvironmentVariable("HOME");
            }
#endif
            var expectedPath = Path.Combine(userProfile, ".nuget", SettingsUtility.DefaultGlobalPackagesFolderPath);

            // Act
            var globalPackagesFolderPath = SettingsUtility.GetGlobalPackagesFolder(NullSettings.Instance);

            // Assert
            globalPackagesFolderPath.Should().Be(expectedPath);
        }
Exemple #18
0
        public NuGetViewModel(ITelemetryProvider telemetryProvider)
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
        {
            try
            {
                ISettings settings;

                try
                {
                    settings = Settings.LoadDefaultSettings(
                        root: null,
                        configFileName: null,
                        machineWideSettings: new XPlatMachineWideSetting());
                }
                catch (NuGetConfigurationException ex)
                {
                    telemetryProvider.ReportError(ex);

                    // create default settings using a non-existent config file
                    settings = new Settings(nameof(RoslynPad));
                }

                GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
                _configFilePaths    = SettingsUtility.GetConfigFilePaths(settings);
                _packageSources     = SettingsUtility.GetEnabledSources(settings);

                DefaultCredentialServiceUtility.SetupDefaultCredentialService(NullLogger.Instance, nonInteractive: false);

                var sourceProvider = new PackageSourceProvider(settings);
                _sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(sourceProvider);
            }
            catch (Exception e)
            {
                _initializationException = ExceptionDispatchInfo.Capture(e);
            }
        }
Exemple #19
0
        public async Task <FileInfo> DownloadAsync(string packageId, NuGetVersion?packageVersion, Uri feedUrl, CancellationToken cancellationToken)
        {
            if (feedUrl is null)
            {
                throw new ArgumentNullException(nameof(feedUrl));
            }

            var             packageSource    = new PackageSource(feedUrl.ToString());
            var             sourceRepository = Repository.Factory.GetCoreV3(packageSource);
            PackageIdentity packageIdentity;

            if (packageVersion != null)
            {
                packageIdentity = new PackageIdentity(packageId, packageVersion);
            }
            else
            {
                packageIdentity = await GetPackageIdentityAsync(packageId, sourceRepository, cancellationToken).ConfigureAwait(false);
            }
            var globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(_settings);
            var downloadResource     = await sourceRepository.GetResourceAsync <DownloadResource>(cancellationToken).ConfigureAwait(false);

            var result = await downloadResource.GetDownloadResourceResultAsync(packageIdentity, new PackageDownloadContext(_sourceCacheContext), globalPackagesFolder, _logger, cancellationToken).ConfigureAwait(false);

            if (result.Status != DownloadResourceResultStatus.Available)
            {
                throw new UnavailableException($"The package {packageIdentity} was not found on {sourceRepository.PackageSource}.");
            }
            if (!(result.PackageStream is FileStream fileStream))
            {
                throw new InvalidOperationException($"The package stream is expected to be a {nameof(FileStream)} but is a {result.PackageStream?.GetType()}.");
            }
            await result.PackageStream.DisposeAsync().ConfigureAwait(false);

            return(new FileInfo(fileStream.Name));
        }
Exemple #20
0
        Task OpenReadmeFiles(
            NuGetProject nuGetProject,
            PackageIdentity package,
            NuGet.ProjectManagement.ExecutionContext executionContext,
            CancellationToken token)
        {
            //packagesPath is different for project.json vs Packages.config scenarios. So check if the project is a build-integrated project
            var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;
            var readmeFilePath         = String.Empty;

            if (buildIntegratedProject != null)
            {
                var packageFolderPath = BuildIntegratedProjectUtility.GetPackagePathFromGlobalSource(
                    SettingsUtility.GetGlobalPackagesFolder(settings),
                    package);

                if (Directory.Exists(packageFolderPath))
                {
                    readmeFilePath = Path.Combine(packageFolderPath, Constants.ReadmeFileName);
                }
            }
            else
            {
                var packagePath = packageManager.PackagesFolderNuGetProject.GetInstalledPackageFilePath(package);
                if (File.Exists(packagePath))
                {
                    readmeFilePath = Path.Combine(Path.GetDirectoryName(packagePath), Constants.ReadmeFileName);
                }
            }

            if (File.Exists(readmeFilePath) && !token.IsCancellationRequested)
            {
                return(executionContext.OpenFile(readmeFilePath));
            }
            return(Task.FromResult(0));
        }
Exemple #21
0
        public void GetGlobalPackagesFolder_FromNuGetConfig()
        {
            // Arrange
            var config = @"<?xml version='1.0' encoding='utf-8'?>
<configuration>
    <config>
        <add key='globalPackagesFolder' value='a' />
    </config>
</configuration>";

            var nugetConfigPath = "NuGet.Config";

            using (var mockBaseDirectory = TestDirectory.Create())
            {
                SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config);
                var settings = new Settings(mockBaseDirectory);

                // Act
                var globalPackagesFolderPath = SettingsUtility.GetGlobalPackagesFolder(settings);

                // Assert
                globalPackagesFolderPath.Should().Be(Path.Combine(mockBaseDirectory, "a"));
            }
        }
        /// <summary>
        /// Restore projects with project.json and create the lock files.
        /// </summary>
        /// <param name="buildEnabledProjects">Projects containing project.json</param>
        /// <param name="forceRestore">Force the restore to write out the lock files.
        /// This is used for rebuilds.</param>
        /// <returns></returns>
        private async Task RestoreBuildIntegratedProjectsAsync(
            string solutionDirectory,
            List <BuildIntegratedProjectSystem> buildEnabledProjects,
            bool forceRestore,
            bool isSolutionAvailable)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (buildEnabledProjects.Any() && IsConsentGranted(Settings))
            {
                if (!isSolutionAvailable)
                {
                    var globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(Settings);
                    if (!Path.IsPathRooted(globalPackagesFolder))
                    {
                        var message = string.Format(
                            CultureInfo.CurrentCulture,
                            NuGet.PackageManagement.VisualStudio.Strings.RelativeGlobalPackagesFolder,
                            globalPackagesFolder);

                        WriteLine(VerbosityLevel.Quiet, message);

                        // Cannot restore packages since globalPackagesFolder is a relative path
                        // and the solution is not available
                        return;
                    }
                }

                var enabledSources = SourceRepositoryProvider.GetRepositories().ToList();

                // Cache p2ps discovered from DTE
                var referenceContext = new ExternalProjectReferenceContext(logger: this);

                // No-op all project closures are up to date and all packages exist on disk.
                if (await IsRestoreRequired(buildEnabledProjects, forceRestore, referenceContext))
                {
                    var waitDialogFactory
                        = ServiceLocator.GetGlobalService <SVsThreadedWaitDialogFactory,
                                                           IVsThreadedWaitDialogFactory>();

                    // NOTE: During restore for build integrated projects,
                    //       We might show the dialog even if there are no packages to restore
                    // When both currentStep and totalSteps are 0, we get a marquee on the dialog
                    using (var threadedWaitDialogSession = waitDialogFactory.StartWaitDialog(
                               waitCaption: Resources.DialogTitle,
                               initialProgress: new ThreadedWaitDialogProgressData(Resources.RestoringPackages,
                                                                                   string.Empty,
                                                                                   string.Empty,
                                                                                   isCancelable: true,
                                                                                   currentStep: 0,
                                                                                   totalSteps: 0)))
                    {
                        // Display the restore opt out message if it has not been shown yet
                        DisplayOptOutMessage();

                        Token = threadedWaitDialogSession.UserCancellationToken;
                        ThreadedWaitDialogProgress = threadedWaitDialogSession.Progress;

                        // Cache resources between requests
                        var providerCache = new RestoreCommandProvidersCache();
                        var tasks         = new List <Task <KeyValuePair <string, Exception> > >();
                        var maxTasks      = 4;

                        // Restore packages and create the lock file for each project
                        foreach (var project in buildEnabledProjects)
                        {
                            // Mark this as having missing packages so that we will not
                            // display a noop message in the summary
                            _hasMissingPackages    = true;
                            _displayRestoreSummary = true;

                            if (tasks.Count >= maxTasks)
                            {
                                await ProcessTask(tasks);
                            }

                            // Skip further restores if the user has clicked cancel
                            if (!Token.IsCancellationRequested)
                            {
                                var projectName = NuGetProject.GetUniqueNameOrName(project);

                                // Restore and create a project.lock.json file
                                tasks.Add(RestoreProject(projectName, async() =>
                                                         await BuildIntegratedProjectRestoreAsync(
                                                             project,
                                                             solutionDirectory,
                                                             enabledSources,
                                                             referenceContext,
                                                             providerCache,
                                                             Token)));
                            }
                        }

                        // Wait for the remaining tasks
                        while (tasks.Count > 0)
                        {
                            await ProcessTask(tasks);
                        }

                        if (Token.IsCancellationRequested)
                        {
                            _canceled = true;
                        }
                    }
                }
            }
        }
        private async Task RestorePackageSpecProjectsAsync(
            List <IDependencyGraphProject> projects,
            bool forceRestore,
            bool isSolutionAvailable,
            RestoreOperationSource restoreSource,
            CancellationToken token)
        {
            // Only continue if there are some build integrated type projects.
            if (!(projects.Any(project => project is BuildIntegratedNuGetProject)))
            {
                return;
            }

            if (_packageRestoreConsent.IsGranted)
            {
                if (!isSolutionAvailable)
                {
                    var globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(_settings);
                    if (!Path.IsPathRooted(globalPackagesFolder))
                    {
                        await _logger.DoAsync((l, _) =>
                        {
                            var message = string.Format(
                                CultureInfo.CurrentCulture,
                                Resources.RelativeGlobalPackagesFolder,
                                globalPackagesFolder);

                            l.WriteLine(VerbosityLevel.Quiet, message);
                        });

                        // Cannot restore packages since globalPackagesFolder is a relative path
                        // and the solution is not available
                        return;
                    }
                }

                // Cache p2ps discovered from DTE
                var cacheContext = new DependencyGraphCacheContext(_logger, _settings);
                var pathContext  = NuGetPathContext.Create(_settings);

                // Get full dg spec
                // TODO: pass this down instead of creating it twice.
                var dgSpec = await DependencyGraphRestoreUtility.GetSolutionRestoreSpec(_solutionManager, cacheContext);

                // Avoid restoring solutions with zero potential PackageReference projects.
                if (DependencyGraphRestoreUtility.IsRestoreRequired(dgSpec))
                {
                    // NOTE: During restore for build integrated projects,
                    //       We might show the dialog even if there are no packages to restore
                    // When both currentStep and totalSteps are 0, we get a marquee on the dialog
                    await _logger.RunWithProgressAsync(
                        async (l, _, t) =>
                    {
                        // Display the restore opt out message if it has not been shown yet
                        await l.WriteHeaderAsync();

                        var sources = _sourceRepositoryProvider
                                      .GetRepositories()
                                      .ToList();

                        var providerCache = new RestoreCommandProvidersCache();
                        Action <SourceCacheContext> cacheModifier = (cache) => { };

                        var restoreSummaries = await DependencyGraphRestoreUtility.RestoreAsync(
                            _solutionManager,
                            cacheContext,
                            providerCache,
                            cacheModifier,
                            sources,
                            forceRestore,
                            dgSpec,
                            l,
                            t);

                        _packageCount      += restoreSummaries.Select(summary => summary.InstallCount).Sum();
                        var isRestoreFailed = restoreSummaries.Any(summary => summary.Success == false);
                        _noOpProjectsCount  = restoreSummaries.Where(summary => summary.NoOpRestore == true).Count();

                        if (isRestoreFailed)
                        {
                            _status = NuGetOperationStatus.Failed;
                        }
                        else if (_noOpProjectsCount < restoreSummaries.Count)
                        {
                            _status = NuGetOperationStatus.Succeeded;
                        }
                    },
                        token);
                }
            }
            else if (restoreSource == RestoreOperationSource.Explicit)
            {
                // Log an error when restore is disabled and user explicitly restore.
                await _logger.DoAsync((l, _) =>
                {
                    l.ShowError(Resources.PackageRefNotRestoredBecauseOfNoConsent);
                });
            }
        }
        /// <summary>
        /// Get the view of installed packages. Use for Get-Package command.
        /// </summary>
        internal static List <PowerShellInstalledPackage> GetPowerShellPackageView(
            Dictionary <NuGetProject, IEnumerable <Packaging.PackageReference> > dictionary,
            ISolutionManager solutionManager,
            Configuration.ISettings settings)
        {
            var views = new List <PowerShellInstalledPackage> ();

            foreach (var entry in dictionary)
            {
                var nugetProject = entry.Key;

                string             packageFolder        = null;
                FolderNuGetProject packageFolderProject = null;

                if (nugetProject is BuildIntegratedNuGetProject)
                {
                    packageFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
                }
                else
                {
                    var project = nugetProject as MSBuildNuGetProject;

                    if (project != null)
                    {
                        packageFolderProject = project.FolderNuGetProject;
                    }
                }

                // entry.Value is an empty list if no packages are installed
                foreach (var package in entry.Value)
                {
                    string installPackagePath = null;
                    string licenseUrl         = null;

                    if (packageFolder != null)
                    {
                        var defaultPackagePathResolver = new VersionFolderPathResolver(packageFolder);
                        installPackagePath = defaultPackagePathResolver.GetPackageFilePath(package.PackageIdentity.Id, package.PackageIdentity.Version);
                    }
                    else if (packageFolderProject != null)
                    {
                        installPackagePath = packageFolderProject.GetInstalledPackageFilePath(package.PackageIdentity);
                    }

                    using (var reader = GetPackageReader(installPackagePath)) {
                        var nuspecReader = new NuspecReader(reader.GetNuspec());
                        licenseUrl = nuspecReader.GetLicenseUrl();
                    }

                    var view = new PowerShellInstalledPackage()
                    {
                        Id = package.PackageIdentity.Id,
                        AsyncLazyVersions = new AsyncLazy <IEnumerable <NuGetVersion> > (() => {
                            return(Task.FromResult <IEnumerable <NuGetVersion> > (new [] { package.PackageIdentity.Version }));
                        }),
                        ProjectName = entry.Key.GetMetadata <string> (NuGetProjectMetadataKeys.Name),
                        LicenseUrl  = licenseUrl
                    };

                    views.Add(view);
                }
            }

            return(views);
        }
Exemple #25
0
        public override async Task <IReadOnlyList <PackageSpec> > GetPackageSpecsAsync(DependencyGraphCacheContext context)
        {
            PackageSpec packageSpec = null;

            if (context == null || !context.PackageSpecCache.TryGetValue(MSBuildProjectPath, out packageSpec))
            {
                packageSpec = JsonPackageSpecReader.GetPackageSpec(ProjectName, JsonConfigPath);
                if (packageSpec == null)
                {
                    throw new InvalidOperationException(
                              string.Format(Strings.ProjectNotLoaded_RestoreFailed, ProjectName));
                }
                var metadata = new ProjectRestoreMetadata();
                packageSpec.RestoreMetadata = metadata;

                metadata.ProjectStyle = ProjectStyle.ProjectJson;
                metadata.OutputPath   = await GetBaseIntermediatePathAsync();

                metadata.ProjectPath       = MSBuildProjectPath;
                metadata.ProjectJsonPath   = packageSpec.FilePath;
                metadata.ProjectName       = packageSpec.Name;
                metadata.ProjectUniqueName = MSBuildProjectPath;

                // Reload the target framework from csproj and update the target framework in packageSpec for restore
                await UpdateInternalTargetFrameworkAsync();

                if (TryGetInternalFramework(out var internalTargetFramework))
                {
                    // Ensure the project json has only one target framework
                    if (packageSpec.TargetFrameworks != null && packageSpec.TargetFrameworks.Count == 1)
                    {
                        var replaceTargetFramework = new TargetFrameworkInformation();
                        replaceTargetFramework.FrameworkName = internalTargetFramework as NuGetFramework;
                        packageSpec.TargetFrameworks[0]      = replaceTargetFramework;
                    }
                }

                var references = (await ProjectServices
                                  .ReferencesReader
                                  .GetProjectReferencesAsync(context.Logger, CancellationToken.None))
                                 .ToList();

                if (references != null && references.Count > 0)
                {
                    // Add msbuild reference groups for each TFM in the project
                    foreach (var framework in packageSpec.TargetFrameworks.Select(e => e.FrameworkName))
                    {
                        metadata.TargetFrameworks.Add(new ProjectRestoreMetadataFrameworkInfo(framework));
                    }

                    foreach (var reference in references)
                    {
                        // This reference applies to all frameworks
                        // Include/exclude flags may be applied later when merged with project.json
                        // Add the reference for all TFM groups, there are no conditional project
                        // references in UWP. There should also be just one TFM.
                        foreach (var frameworkInfo in metadata.TargetFrameworks)
                        {
                            frameworkInfo.ProjectReferences.Add(reference);
                        }
                    }
                }
                // Write restore settings to the package spec.
                // For project.json these properties may not come from the project file.
                var settings = context?.Settings ?? NullSettings.Instance;
                packageSpec.RestoreMetadata.PackagesPath    = SettingsUtility.GetGlobalPackagesFolder(settings);
                packageSpec.RestoreMetadata.Sources         = SettingsUtility.GetEnabledSources(settings).AsList();
                packageSpec.RestoreMetadata.FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).AsList();
                packageSpec.RestoreMetadata.ConfigFilePaths = SettingsUtility.GetConfigFilePaths(settings).AsList();

                context?.PackageSpecCache.Add(MSBuildProjectPath, packageSpec);
            }

            return(new[] { packageSpec });
        }
        public async Task GetPackageSpecsAsync_ReadSettingsWithFullPaths(string restorePackagesPath, string sources, string fallbackFolders)
        {
            // Arrange
            using (var testDirectory = TestDirectory.Create())
            {
                var projectAdapter = CreateProjectAdapter(testDirectory);
                Mock.Get(projectAdapter)
                .SetupGet(x => x.RestorePackagesPath)
                .Returns(restorePackagesPath);

                Mock.Get(projectAdapter)
                .SetupGet(x => x.RestoreSources)
                .Returns(sources);

                Mock.Get(projectAdapter)
                .SetupGet(x => x.RestoreFallbackFolders)
                .Returns(fallbackFolders);

                var projectServices = new TestProjectSystemServices();

                var testProject = new LegacyPackageReferenceProject(
                    projectAdapter,
                    Guid.NewGuid().ToString(),
                    projectServices,
                    _threadingService);

                var settings = NullSettings.Instance;
                var testDependencyGraphCacheContext = new DependencyGraphCacheContext(NullLogger.Instance, settings);

                await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

                // Act
                var packageSpecs = await testProject.GetPackageSpecsAsync(testDependencyGraphCacheContext);

                // Assert
                Assert.NotNull(packageSpecs);
                var actualRestoreSpec = packageSpecs.Single();
                SpecValidationUtility.ValidateProjectSpec(actualRestoreSpec);

                // Assert packagespath
                Assert.Equal(restorePackagesPath != null ? restorePackagesPath : SettingsUtility.GetGlobalPackagesFolder(settings), actualRestoreSpec.RestoreMetadata.PackagesPath);

                // assert sources
                var specSources     = actualRestoreSpec.RestoreMetadata.Sources.Select(e => e.Source);
                var expectedSources = sources != null?MSBuildStringUtility.Split(sources) : SettingsUtility.GetEnabledSources(settings).Select(e => e.Source);

                Assert.True(Enumerable.SequenceEqual(expectedSources.OrderBy(t => t), specSources.OrderBy(t => t)));

                // assert fallbackfolders
                var specFallback    = actualRestoreSpec.RestoreMetadata.FallbackFolders;
                var expectedFolders = fallbackFolders != null?MSBuildStringUtility.Split(fallbackFolders) : SettingsUtility.GetFallbackPackageFolders(settings);

                Assert.True(Enumerable.SequenceEqual(expectedFolders.OrderBy(t => t), specFallback.OrderBy(t => t)));

                // Verify
                Mock.Get(projectAdapter)
                .Verify(x => x.RestorePackagesPath, Times.Once);
                Mock.Get(projectAdapter)
                .Verify(x => x.RestoreSources, Times.Once);
                Mock.Get(projectAdapter)
                .Verify(x => x.RestoreFallbackFolders, Times.Once);
            }
        }
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            // Log Inputs
            BuildTasksUtility.LogInputParam(log, nameof(ProjectUniqueName), ProjectUniqueName);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSources), RestoreSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPath), RestorePackagesPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFolders), RestoreFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreConfigFile), RestoreConfigFile);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSolutionDirectory), RestoreSolutionDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPathOverride), RestorePackagesPathOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSourcesOverride), RestoreSourcesOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFoldersOverride), RestoreFallbackFoldersOverride);
            BuildTasksUtility.LogInputParam(log, nameof(MSBuildStartupDirectory), MSBuildStartupDirectory);

            try
            {
                // Validate inputs
                if (RestoreSourcesOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                {
                    // Fail due to invalid source combination
                    return(false);
                }

                if (RestoreFallbackFoldersOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                {
                    // Fail due to invalid fallback combination
                    return(false);
                }

                // Settings
                // Find the absolute path of nuget.config, this should only be set on the command line. Setting the path in project files
                // is something that could happen, but it is not supported.
                var absoluteConfigFilePath = GetGlobalAbsolutePath(RestoreConfigFile);
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, Path.GetDirectoryName(ProjectUniqueName), absoluteConfigFilePath, _machineWideSettings);
                OutputConfigFilePaths = SettingsUtility.GetConfigFilePaths(settings).ToArray();

                // PackagesPath
                OutputPackagesPath = RestoreSettingsUtils.GetValue(
                    () => GetGlobalAbsolutePath(RestorePackagesPathOverride),
                    () => string.IsNullOrEmpty(RestorePackagesPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestorePackagesPath),
                    () => SettingsUtility.GetGlobalPackagesFolder(settings));

                // Sources
                var currentSources = RestoreSettingsUtils.GetValue(
                    () => RestoreSourcesOverride?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => GetGlobalAbsolutePath(e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreSources) ? new string[0] : null,
                    () => RestoreSources?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => (new PackageSourceProvider(settings)).LoadPackageSources().Where(e => e.IsEnabled).Select(e => e.Source).ToArray());

                // Append additional sources
                // Escape strings to avoid xplat path issues with msbuild.
                var additionalProjectSources = MSBuildRestoreUtility.AggregateSources(
                    values: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectSources"),
                    excludeValues: Enumerable.Empty <string>())
                                               .Select(MSBuildRestoreUtility.FixSourcePath)
                                               .ToArray();

                OutputSources = AppendItems(currentSources, additionalProjectSources);

                // Fallback folders
                var currentFallbackFolders = RestoreSettingsUtils.GetValue(
                    () => RestoreFallbackFoldersOverride?.Select(e => GetGlobalAbsolutePath(e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreFallbackFolders) ? new string[0] : null,
                    () => RestoreFallbackFolders?.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => SettingsUtility.GetFallbackPackageFolders(settings).ToArray());

                // Append additional fallback folders after removing excluded folders
                var additionalProjectFallbackFolders = MSBuildRestoreUtility.AggregateSources(
                    values: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFolders"),
                    excludeValues: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFoldersExcludes"))
                                                       .ToArray();

                OutputFallbackFolders = AppendItems(currentFallbackFolders, additionalProjectFallbackFolders);
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            BuildTasksUtility.LogOutputParam(log, nameof(OutputPackagesPath), OutputPackagesPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputSources), OutputSources);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputFallbackFolders), OutputFallbackFolders);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputConfigFilePaths), OutputConfigFilePaths);

            return(true);
        }
Exemple #28
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;
                }
            }
        }
        public NuGetSourceRepositoryProvider(ISettings settings, ICakeConfiguration config, PackageReference package, string packagesRoot)
        {
            if (settings is null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            if (config is null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            if (package is null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            // Create the default v3 resource provider
            _resourceProviders = new List <Lazy <INuGetResourceProvider> >();
            _resourceProviders.AddRange(Repository.Provider.GetCoreV3());

            // Add repositories
            var sourceComparer = new NuGetSourceRepositoryComparer();

            _repositories        = new HashSet <SourceRepository>(sourceComparer);
            _primaryRepositories = new HashSet <SourceRepository>(sourceComparer);
            _localRepositories   = new HashSet <SourceRepository>(sourceComparer);
            _localRepositories.Add(CreateRepository(packagesRoot));
            _localRepositories.Add(CreateRepository(SettingsUtility.GetGlobalPackagesFolder(settings)));
            _localRepositories.AddRange(SettingsUtility.GetFallbackPackageFolders(settings).Select(CreateRepository));

            var packageSources = new PackageSourceProvider(settings).LoadPackageSources().ToList();

            if (package.Address != null)
            {
                var repository = GetOrCreateRepository(package.Address.AbsoluteUri);

                // Sources specified in directive is always primary.
                _repositories.Add(repository);
                _primaryRepositories.Add(repository);
            }

            var nugetSources = config.GetValue(Constants.NuGet.Source);

            if (!string.IsNullOrEmpty(nugetSources))
            {
                foreach (var nugetSource in nugetSources.Split(';'))
                {
                    if (!string.IsNullOrWhiteSpace(nugetSource))
                    {
                        var repository = GetOrCreateRepository(nugetSource);
                        _repositories.Add(repository);

                        // If source is not specified in directive, add it as primary source.
                        if (package.Address == null)
                        {
                            _primaryRepositories.Add(repository);
                        }
                    }
                }
            }
            else
            {
                // Only add sources added via NuGet.config if nuget_source configuration value is not specified.
                foreach (var source in packageSources)
                {
                    if (source.IsEnabled)
                    {
                        var repository = CreateRepository(source);
                        _repositories.Add(repository);

                        // If source is not specified in directive, add it as primary source.
                        if (package.Address == null)
                        {
                            _primaryRepositories.Add(repository);
                        }
                    }
                }
            }

            SourceRepository GetOrCreateRepository(string source)
            {
                var packageSource = packageSources
                                    .Where(p => p.IsEnabled)
                                    .FirstOrDefault(p => p.Source.Equals(source, StringComparison.OrdinalIgnoreCase));

                return(packageSource == null?
                       CreateRepository(source) :
                           CreateRepository(packageSource));
            }
        }
Exemple #30
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");
            }
        }