Beispiel #1
0
        public static async Task ExecuteInitPs1ScriptsAsync(
            BuildIntegratedNuGetProject project,
            IEnumerable <PackageIdentity> packages,
            FallbackPackagePathResolver pathResolver,
            INuGetProjectContext projectContext)
        {
            // Find all dependencies in sorted order
            var sortedPackages = await BuildIntegratedProjectUtility.GetOrderedProjectPackageDependencies(project);

            // Keep track of the packages that need to be executed.
            var packagesToExecute = new HashSet <PackageIdentity>(packages, PackageIdentity.Comparer);

            // Use the ordered packages to run init.ps1 for the specified packages.
            foreach (var package in sortedPackages)
            {
                if (packagesToExecute.Remove(package))
                {
                    var packageInstallPath = pathResolver.GetPackageDirectory(package.Id, package.Version);

                    if (packageInstallPath == null)
                    {
                        continue;
                    }

                    await project.ExecuteInitScriptAsync(
                        package,
                        packageInstallPath,
                        projectContext,
                        throwOnFailure : false);
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Initialize a new instance of <see cref="NugetStore"/>.
        /// </summary>
        /// <param name="oldRootDirectory">The location of the Nuget store.</param>
        public NugetStore(string oldRootDirectory)
        {
            // Used only for versions before 3.0
            this.oldRootDirectory = oldRootDirectory;

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

            // Add dev source
            CheckPackageSource("Xenko", DefaultPackageSource);

            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);
        }
Beispiel #3
0
        public void FallbackPackagePathResolver_MissingPackageWithFallbacks()
        {
            // Arrange
            using (var mockBaseDirectory = TestDirectory.Create())
            {
                var userFolder      = Path.Combine(mockBaseDirectory, "global");
                var fallbackFolders = new List <string>()
                {
                    Path.Combine(mockBaseDirectory, "fallback1"),
                    Path.Combine(mockBaseDirectory, "fallback2"),
                };

                Directory.CreateDirectory(userFolder);

                foreach (var fallback in fallbackFolders)
                {
                    Directory.CreateDirectory(fallback);
                }

                var resolver = new FallbackPackagePathResolver(userFolder, fallbackFolders);

                // Act
                var path = resolver.GetPackageDirectory("a", "1.0.0");

                // Assert
                Assert.Null(path);
            }
        }
Beispiel #4
0
        public ScriptDependencyContext ReadDependencyContext(string pathToAssetsFile)
        {
            var lockFile = GetLockFile(pathToAssetsFile);

            // Since we execute "dotnet restore -r [rid]" we get two targets in the lock file.
            // The second target is the one containing the runtime deps for the given RID.
            var target              = GetLockFileTarget(lockFile);
            var targetLibraries     = target.Libraries;
            var packageFolders      = lockFile.PackageFolders.Select(lfi => lfi.Path).ToArray();
            var userPackageFolder   = packageFolders.First();
            var fallbackFolders     = packageFolders.Skip(1);
            var packagePathResolver = new FallbackPackagePathResolver(userPackageFolder, fallbackFolders);

            List <ScriptDependency> scriptDependencies = new List <ScriptDependency>();

            foreach (var targetLibrary in targetLibraries)
            {
                var scriptDependency = CreateScriptDependency(targetLibrary.Name, targetLibrary.Version.ToString(), packageFolders, packagePathResolver, targetLibrary);
                if (scriptDependency.CompileTimeDependencyPaths.Any() ||
                    scriptDependency.NativeAssetPaths.Any() ||
                    scriptDependency.RuntimeDependencyPaths.Any() ||
                    scriptDependency.ScriptPaths.Any())
                {
                    scriptDependencies.Add(scriptDependency);
                }
            }

            return(new ScriptDependencyContext(scriptDependencies.ToArray()));
        }
        public static void UpdatePackageReferenceMetadata(
            PackageSpec packageSpec,
            FallbackPackagePathResolver pathResolver,
            PackageIdentity package)
        {
            var info                  = pathResolver.GetPackageInfo(package.Id, package.Version);
            var nuspecFilePath        = info?.PathResolver.GetManifestFilePath(package.Id, package.Version);
            var nuspecReader          = new NuspecReader(nuspecFilePath);
            var developmentDependency = nuspecReader.GetDevelopmentDependency();

            if (developmentDependency)
            {
                foreach (var frameworkInfo in packageSpec.TargetFrameworks
                         .OrderBy(framework => framework.FrameworkName.ToString(),
                                  StringComparer.Ordinal))
                {
                    var dependency = frameworkInfo.Dependencies.First(dep => dep.Name.Equals(package.Id, StringComparison.OrdinalIgnoreCase));

                    if (dependency?.SuppressParent == LibraryIncludeFlagUtils.DefaultSuppressParent &&
                        dependency?.IncludeType == LibraryIncludeFlags.All)
                    {
                        dependency.SuppressParent = LibraryIncludeFlags.All;
                        dependency.IncludeType    = LibraryIncludeFlags.All & ~LibraryIncludeFlags.Runtime;
                    }
                }
            }
        }
Beispiel #6
0
            /// <summary>
            /// Attempts to find a NuGet package if it is already installed.
            /// </summary>
            private static bool TryGetMSBuildSdkPackageInfo(FallbackPackagePathResolver fallbackPackagePathResolver, string id, NuGetVersion version, out string installedPath, out string installedVersion)
            {
                // Find the package
                var packageInfo = fallbackPackagePathResolver.GetPackageInfo(id, version);

                if (packageInfo == null)
                {
                    installedPath    = null;
                    installedVersion = null;
                    return(false);
                }

                // Get the installed path and add the expected "Sdk" folder.  Windows file systems are not case sensitive
                installedPath = Path.Combine(packageInfo.PathResolver.GetInstallPath(packageInfo.Id, packageInfo.Version), "Sdk");


                if (!NuGet.Common.RuntimeEnvironmentHelper.IsWindows && !Directory.Exists(installedPath))
                {
                    // Fall back to lower case "sdk" folder in case the file system is case sensitive
                    installedPath = Path.Combine(packageInfo.PathResolver.GetInstallPath(packageInfo.Id, packageInfo.Version), "sdk");
                }

                installedVersion = packageInfo.Version.ToString();

                return(true);
            }
Beispiel #7
0
        private async Task <IVsPathContext> GetPathContextFromAssetsFileAsync(
            NuGetProject nuGetProject, CancellationToken token)
        {
            // It's possible that this project isn't a build integrated NuGet project at all. That is, this project may
            // be a packages.config project.
            var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;

            if (buildIntegratedProject == null)
            {
                return(null);
            }

            // It's possible the lock file doesn't exist or it's an older format that doesn't have the package folders
            // property persisted.
            var lockFile = await _getLockFileOrNullAsync(buildIntegratedProject);

            if (lockFile == null ||
                lockFile.PackageFolders == null ||
                lockFile.PackageFolders.Count == 0)
            {
                return(null);
            }

            // The user packages folder is always the first package folder. Subsequent package folders are always
            // fallback package folders.
            var packageFolders = lockFile
                                 .PackageFolders
                                 .Select(lockFileItem => lockFileItem.Path)
                                 .ToList();

            var userPackageFolder      = packageFolders[0];
            var fallbackPackageFolders = packageFolders.Skip(1);

            if (lockFile.Libraries == null ||
                lockFile.Libraries.Count == 0)
            {
                return(new VsPathContext(userPackageFolder, fallbackPackageFolders));
            }

            var fppr = new FallbackPackagePathResolver(userPackageFolder, fallbackPackageFolders);

            var trie = new PathLookupTrie <string>();

            foreach (var pid in lockFile
                     .Libraries
                     .Where(l => l.Type == LibraryType.Package)
                     .Select(l => new PackageIdentity(l.Name, l.Version)))
            {
                var packageInstallPath = fppr.GetPackageDirectory(pid.Id, pid.Version);
                if (packageInstallPath != null)
                {
                    trie[packageInstallPath] = packageInstallPath;
                }
            }

            return(new VsIndexedPathContext(
                       userPackageFolder,
                       fallbackPackageFolders,
                       trie));
        }
Beispiel #8
0
        /// <summary>
        /// Initialize a new instance of <see cref="NugetStore"/>.
        /// </summary>
        /// <param name="oldRootDirectory">The location of the Nuget store.</param>
        public NugetStore(string oldRootDirectory)
        {
            // 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 ");

            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);
        }
Beispiel #9
0
        private string GetCommandFilePath(
            IEnumerable <string> packageFolders,
            LockFileTargetLibrary toolLibrary,
            LockFileItem runtimeAssembly)
        {
            var packageFoldersCount    = packageFolders.Count();
            var userPackageFolder      = packageFoldersCount == 1 ? string.Empty : packageFolders.First();
            var fallbackPackageFolders = packageFoldersCount > 1 ? packageFolders.Skip(1) : packageFolders;

            var packageDirectory = new FallbackPackagePathResolver(userPackageFolder, fallbackPackageFolders)
                                   .GetPackageDirectory(toolLibrary.Name, toolLibrary.Version);

            if (packageDirectory == null)
            {
                throw new GracefulException(string.Format(
                                                LocalizableStrings.CommandAssembliesNotFound,
                                                toolLibrary.Name));
            }

            var filePath = Path.Combine(
                packageDirectory,
                PathUtility.GetPathWithDirectorySeparator(runtimeAssembly.Path));

            return(filePath);
        }
Beispiel #10
0
        private string GetPackageInstalledPath(PackageIdentity packageIdentity)
        {
            var nugetPaths       = NuGetPathContext.Create(Settings);
            var fallbackResolver = new FallbackPackagePathResolver(nugetPaths);

            // Verify the package exists and return the path. Return null otherwise.
            return(fallbackResolver.GetPackageDirectory(packageIdentity.Id, packageIdentity.Version));
        }
        private async Task <IVsPathContext> GetPathContextFromAssetsFileAsync(
            NuGetProject nuGetProject, CancellationToken token)
        {
            // It's possible that this project isn't a build integrated NuGet project at all. That is, this project may
            // be a packages.config project.
            var buildIntegratedProject = nuGetProject as BuildIntegratedNuGetProject;

            if (buildIntegratedProject == null)
            {
                return(null);
            }

            var lockFile = await _getLockFileOrNullAsync(buildIntegratedProject);

            if ((lockFile?.PackageFolders?.Count ?? 0) == 0)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, VsResources.PathContext_LockFileError));
            }

            // The user packages folder is always the first package folder. Subsequent package folders are always
            // fallback package folders.
            var packageFolders = lockFile
                                 .PackageFolders
                                 .Select(lockFileItem => lockFileItem.Path)
                                 .ToList();

            var userPackageFolder      = packageFolders[0];
            var fallbackPackageFolders = packageFolders.Skip(1);

            if (lockFile.Libraries == null ||
                lockFile.Libraries.Count == 0)
            {
                return(new VsPathContext(userPackageFolder, fallbackPackageFolders));
            }

            var fppr = new FallbackPackagePathResolver(userPackageFolder, fallbackPackageFolders);

            var trie = new PathLookupTrie <string>();

            foreach (var pid in lockFile
                     .Libraries
                     .Where(l => l.Type == LibraryType.Package)
                     .Select(l => new PackageIdentity(l.Name, l.Version)))
            {
                var packageInstallPath = fppr.GetPackageDirectory(pid.Id, pid.Version);
                if (string.IsNullOrEmpty(packageInstallPath))
                {
                    throw new KeyNotFoundException(string.Format(CultureInfo.CurrentCulture, VsResources.PathContext_PackageDirectoryNotFound, pid));
                }

                trie[packageInstallPath] = packageInstallPath;
            }

            return(new VsIndexedPathContext(
                       userPackageFolder,
                       fallbackPackageFolders,
                       trie));
        }
        public IEnumerable <IVsPackageMetadata> GetInstalledPackages()
        {
            var packages = new HashSet <IVsPackageMetadata>(new VsPackageMetadataComparer());

            return(NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate
            {
                // Calls may occur in the template wizard before the solution is actually created,
                // in that case return no projects
                if (_solutionManager != null &&
                    !string.IsNullOrEmpty(_solutionManager.SolutionDirectory))
                {
                    InitializePackageManagerAndPackageFolderPath();

                    foreach (var project in (await _solutionManager.GetNuGetProjectsAsync()))
                    {
                        FallbackPackagePathResolver pathResolver = null;
                        var buildIntegratedProject = project as BuildIntegratedNuGetProject;
                        if (buildIntegratedProject != null)
                        {
                            pathResolver = await GetPackagesPathResolverAsync(buildIntegratedProject);
                        }

                        var installedPackages = await project.GetInstalledPackagesAsync(CancellationToken.None);

                        foreach (var package in installedPackages)
                        {
                            var identity = package.PackageIdentity;

                            if (!identity.HasVersion)
                            {
                                // Currently we are not supporting floating versions
                                // because of that we will skip this package
                                continue;
                            }

                            // find packages using the solution level packages folder
                            string installPath;
                            if (buildIntegratedProject != null)
                            {
                                installPath = pathResolver.GetPackageDirectory(identity.Id, identity.Version);
                            }
                            else
                            {
                                installPath = _packageManager
                                              .PackagesFolderNuGetProject
                                              .GetInstalledPath(identity);
                            }

                            var metadata = new VsPackageMetadata(package.PackageIdentity, installPath);

                            packages.Add(metadata);
                        }
                    }
                }

                return packages;
            }));
        }
Beispiel #13
0
        private ScriptDependency CreateScriptDependency(string name, string version, FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary)
        {
            var runtimeDependencyPaths     = GetRuntimeDependencyPaths(packagePathResolver, targetLibrary);
            var compileTimeDependencyPaths = GetCompileTimeDependencyPaths(packagePathResolver, targetLibrary);
            var nativeAssetPaths           = GetNativeAssetPaths(packagePathResolver, targetLibrary);
            var scriptPaths = GetScriptPaths(packagePathResolver, targetLibrary);

            return(new ScriptDependency(name, version, runtimeDependencyPaths, nativeAssetPaths, compileTimeDependencyPaths.ToArray(), scriptPaths));
        }
Beispiel #14
0
        public async Task FallbackPackagePathResolver_FindPackageInFallbackFolder2SkipMissingHashes()
        {
            // Arrange
            using (var mockBaseDirectory = TestDirectory.Create())
            {
                var userFolder      = Path.Combine(mockBaseDirectory, "global");
                var fallbackFolders = new List <string>()
                {
                    Path.Combine(mockBaseDirectory, "fallback1"),
                    Path.Combine(mockBaseDirectory, "fallback2"),
                };

                Directory.CreateDirectory(userFolder);

                foreach (var fallback in fallbackFolders)
                {
                    Directory.CreateDirectory(fallback);
                }

                var saveMode = PackageSaveMode.Nuspec | PackageSaveMode.Files | PackageSaveMode.Nupkg;

                var targetFolder = fallbackFolders[1];

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    userFolder,
                    saveMode,
                    new PackageIdentity("a", NuGetVersion.Parse("1.0.0")));

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    fallbackFolders[0],
                    saveMode,
                    new PackageIdentity("a", NuGetVersion.Parse("1.0.0")));

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    fallbackFolders[1],
                    saveMode,
                    new PackageIdentity("a", NuGetVersion.Parse("1.0.0")));

                // Remove hashes from the first two folders
                foreach (var root in new[] { userFolder, fallbackFolders[0] })
                {
                    var localResolver = new VersionFolderPathResolver(root);
                    File.Delete(localResolver.GetHashPath("a", NuGetVersion.Parse("1.0.0")));
                }

                var expected = Path.Combine(targetFolder, "a", "1.0.0");

                var resolver = new FallbackPackagePathResolver(userFolder, fallbackFolders);

                // Act
                var path = resolver.GetPackageDirectory("a", "1.0.0");

                // Assert
                Assert.Equal(expected, path);
            }
        }
        /// <summary>
        /// No solution manager provided so only global packages cache will be considered.
        /// </summary>
        public PackageManagementPathResolver()
        {
            var settings    = SettingsLoader.LoadDefaultSettings();
            var pathContext = NuGetPathContext.Create(settings);

            pathResolver = new FallbackPackagePathResolver(pathContext);
            globalPackagesFolderResolver = new VersionFolderPathResolver(pathContext.UserPackageFolder);

            folderNuGetProject = new FolderNuGetProject(pathContext.UserPackageFolder);
        }
        async Task CollectPackagesForBuildIntegratedProjectAsync(
            BuildIntegratedNuGetProject project,
            ISet <PackageIdentity> finishedPackages,
            IList <PackageItem> installedPackages,
            CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            var lockFile = await getLockFileOrNullAsync(project);

            if (lockFile == null)
            {
                return;
            }

            if (lockFile.Libraries == null ||
                lockFile.Libraries.Count == 0)
            {
                return;
            }

            FallbackPackagePathResolver fppr;

            if ((lockFile?.PackageFolders?.Count ?? 0) != 0)
            {
                // The user packages folder is always the first package folder. Subsequent package folders are always
                // fallback package folders.
                var packageFolders = lockFile
                                     .PackageFolders
                                     .Select(lockFileItem => lockFileItem.Path);

                var userPackageFolder      = packageFolders.First();
                var fallbackPackageFolders = packageFolders.Skip(1);

                fppr = new FallbackPackagePathResolver(userPackageFolder, fallbackPackageFolders);
            }
            else
            {
                var pathContext = NuGetPathContext.Create(settings);
                fppr = new FallbackPackagePathResolver(pathContext);
            }

            foreach (var package in BuildIntegratedProjectUtility.GetOrderedLockFilePackageDependencies(lockFile))
            {
                if (!finishedPackages.Contains(package))
                {
                    var installPath = fppr.GetPackageDirectory(package.Id, package.Version);
                    if (!string.IsNullOrEmpty(installPath))
                    {
                        installedPackages.Add(new PackageItem(package, installPath));
                        finishedPackages.Add(package);
                    }
                }
            }
        }
Beispiel #17
0
        public async Task RunToolWithCreateConfigVerifySuccess()
        {
            using (var testContext = new SleetTestContext())
            {
                var dir = Path.Combine(testContext.Root, "project");
                Directory.CreateDirectory(dir);

                var dotnetExe    = GetDotnetPath();
                var exeFile      = new FileInfo(dotnetExe);
                var nupkgsFolder = Path.Combine(exeFile.Directory.Parent.FullName, "artifacts", "nupkgs");

                var sleetNupkg = LocalFolderUtility.GetPackagesV2(nupkgsFolder, "Sleet", NullLogger.Instance)
                                 .OrderByDescending(e => e.Nuspec.GetVersion())
                                 .First();

                var sleetVersion = sleetNupkg.Nuspec.GetVersion().ToNormalizedString();

                var result = await CmdRunner.RunAsync(dotnetExe, dir, "new classlib");

                result.Success.Should().BeTrue();

                var projectPath = Path.Combine(dir, "project.csproj");

                var pathContext  = NuGetPathContext.Create(dir);
                var pathResolver = new FallbackPackagePathResolver(pathContext);

                // Delete restore assets file
                var toolInstallPath = Path.Combine(pathContext.UserPackageFolder, ".tools", "sleet");
                Delete(new DirectoryInfo(toolInstallPath));

                // Delete the tool package itself if it exists
                var toolPackagePath = Path.Combine(pathContext.UserPackageFolder, "sleet", sleetVersion);
                Delete(new DirectoryInfo(toolPackagePath));

                // Add a reference to the tool
                var xml = XDocument.Load(projectPath);
                xml.Root.Add(new XElement(XName.Get("ItemGroup"),
                                          new XElement(XName.Get("DotNetCliToolReference"),
                                                       new XAttribute("Include", "Sleet"),
                                                       new XAttribute("Version", sleetVersion))));
                xml.Save(projectPath);

                // Restore the tool
                result = await CmdRunner.RunAsync(dotnetExe, dir, $"restore --source {nupkgsFolder}");

                result.Success.Should().BeTrue();

                // Run the tool
                result = await CmdRunner.RunAsync(dotnetExe, dir, $"sleet createconfig");

                result.Success.Should().BeTrue();

                File.Exists(Path.Combine(dir, "sleet.json")).Should().BeTrue();
            }
        }
        public PackageManagementPathResolver(IMonoDevelopSolutionManager solutionManager)
        {
            var pathContext = NuGetPathContext.Create(solutionManager.Settings);

            pathResolver = new FallbackPackagePathResolver(pathContext);
            globalPackagesFolderResolver = new VersionFolderPathResolver(pathContext.UserPackageFolder);

            string packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(solutionManager, solutionManager.Settings);

            folderNuGetProject = new FolderNuGetProject(packagesFolderPath);
        }
Beispiel #19
0
        private static string[] GetCompileTimeDependencyPaths(FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary)
        {
            var compileTimeDependencyPaths = new List <string>();

            foreach (var lockFileItem in targetLibrary.CompileTimeAssemblies.Where(cta => !cta.Path.EndsWith("_._")))
            {
                var fullPath = ResolveFullPath(packagePathResolver, targetLibrary.Name, targetLibrary.Version.ToString(), lockFileItem.Path);
                compileTimeDependencyPaths.Add(fullPath);
            }
            return(compileTimeDependencyPaths.ToArray());
        }
Beispiel #20
0
        private string[] GetNativeAssetPaths(FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary)
        {
            List <string> nativeAssetPaths = new List <string>();

            foreach (var runtimeTarget in targetLibrary.NativeLibraries.Where(lfi => !lfi.Path.EndsWith("_._")))
            {
                var fullPath = ResolveFullPath(packagePathResolver, targetLibrary.Name, targetLibrary.Version.ToString(), runtimeTarget.Path);
                nativeAssetPaths.Add(fullPath);
            }

            return(nativeAssetPaths.ToArray());
        }
Beispiel #21
0
        public PackageDependencyProvider(INuGetPathContext nugetPathContext, FrameworkReferenceResolver frameworkReferenceResolver)
        {
            if (nugetPathContext != null)
            {
                _packagePathResolver = new FallbackPackagePathResolver(nugetPathContext);

                // This resolver is only used for building file names, so that base path is not required.
                _versionFolderPathResolver = new VersionFolderPathResolver(path: null);
            }

            _frameworkReferenceResolver = frameworkReferenceResolver;
        }
Beispiel #22
0
        private async Task <IVsPathContext> GetPathContextFromProjectLockFileAsync(
            string lockFilePath, CancellationToken token)
        {
            var lockFile = _getLockFileOrNull(lockFilePath);

            if ((lockFile?.PackageFolders?.Count ?? 0) == 0)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, VsResources.PathContext_LockFileError));
            }

            // switch to a background thread to process packages data
            await TaskScheduler.Default;

            // The user packages folder is always the first package folder. Subsequent package folders are always
            // fallback package folders.
            var packageFolders = lockFile
                                 .PackageFolders
                                 .Select(lockFileItem => lockFileItem.Path)
                                 .ToList();

            var userPackageFolder      = packageFolders[0];
            var fallbackPackageFolders = packageFolders.Skip(1);

            if (lockFile.Libraries == null ||
                lockFile.Libraries.Count == 0)
            {
                return(new VsPathContext(userPackageFolder, fallbackPackageFolders));
            }

            var fppr = new FallbackPackagePathResolver(userPackageFolder, fallbackPackageFolders);

            var trie = new PathLookupTrie <string>();

            foreach (var pid in lockFile
                     .Libraries
                     .Where(l => l.Type == LibraryType.Package)
                     .Select(l => new PackageIdentity(l.Name, l.Version)))
            {
                var packageInstallPath = fppr.GetPackageDirectory(pid.Id, pid.Version);
                if (string.IsNullOrEmpty(packageInstallPath))
                {
                    throw new KeyNotFoundException(string.Format(CultureInfo.CurrentCulture, VsResources.PathContext_PackageDirectoryNotFound, pid));
                }

                trie[packageInstallPath] = packageInstallPath;
            }

            return(new VsIndexedPathContext(
                       userPackageFolder,
                       fallbackPackageFolders,
                       trie));
        }
Beispiel #23
0
        /// <summary>
        /// Initialize NugetStore using <paramref name="rootDirectory"/> as location of the local copies,
        /// and a configuration file <paramref name="configFile"/> as well as an override configuration
        /// file <paramref name="overrideFile"/> where all settings of <paramref name="overrideFile"/> also
        /// presents in <paramref name="configFile"/> take precedence.
        /// </summary>
        /// <param name="rootDirectory">The location of the Nuget store.</param>
        public NugetStore(string rootDirectory, string configFile = DefaultConfig)
        {
            RootDirectory = rootDirectory ?? throw new ArgumentNullException(nameof(rootDirectory));

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

            // Add dev source
            Directory.CreateDirectory(Environment.ExpandEnvironmentVariables(DevSource));
            CheckPackageSource("Xenko Dev", DevSource);
            CheckPackageSource("Xenko", DefaultPackageSource);

            // Override file does not exist, fallback to default config file
            var configFileName = configFile;
            var configFilePath = Path.Combine(rootDirectory, configFileName);

            if (File.Exists(configFilePath))
            {
                localSettings = NuGet.Configuration.Settings.LoadDefaultSettings(rootDirectory, configFileName, machineWideSettings: null);

                // Replicate packageSources in user config so that NuGet restore can find them as well
                foreach (var x in localSettings.GetSettingValues("packageSources", true))
                {
                    CheckPackageSource(x.Key, x.Value);
                }
            }

            InstallPath = SettingsUtility.GetGlobalPackagesFolder(settings);

            var pathContext = NuGetPathContext.Create(settings);

            InstalledPathResolver = new FallbackPackagePathResolver(pathContext);
            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);

            manager = new NuGetPackageManager(sourceRepositoryProvider, settings, InstallPath);
            // Override PackagePathResolver
            // Workaround for https://github.com/NuGet/Home/issues/6639
            manager.PackagesFolderNuGetProject.GetType().GetProperty("PackagePathResolver", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(manager.PackagesFolderNuGetProject, new PackagePathResolverV3(InstallPath));

            // Obsolete (Xenko 2.x support)
            InstallPathV2  = Path.Combine(RootDirectory, DefaultGamePackagesDirectory);
            managerV2      = new NuGetPackageManager(sourceRepositoryProvider, settings, InstallPathV2);
            PathResolverV2 = new PackagePathResolver(InstallPathV2);
        }
Beispiel #24
0
        public static string GetPackageDirectory(this LockFile lockFile, LockFileTargetLibrary library)
        {
            var packageFolders = lockFile.GetNormalizedPackageFolders();

            var packageFoldersCount    = packageFolders.Count();
            var userPackageFolder      = packageFoldersCount == 1 ? string.Empty : packageFolders.First();
            var fallbackPackageFolders = packageFoldersCount > 1 ? packageFolders.Skip(1) : packageFolders;

            var packageDirectory = new FallbackPackagePathResolver(userPackageFolder, fallbackPackageFolders)
                                   .GetPackageDirectory(library.Name, library.Version);

            return(packageDirectory);
        }
Beispiel #25
0
        private static string ResolvePackageFullPath(FallbackPackagePathResolver packagePathResolver, string name, string version)
        {
            var packageFolder = packagePathResolver.GetPackageDirectory(name, version);

            if (packageFolder != null)
            {
                return(packageFolder);
            }

            string message = $@"The requested package ({name},{version}) was not found in the global Nuget cache(s).
. Try executing/publishing the script again with the '--no-cache' option";

            throw new InvalidOperationException(message);
        }
Beispiel #26
0
        private static string ResolveFullPath(FallbackPackagePathResolver packagePathResolver, string name, string version, string referencePath)
        {
            var packageFolder = ResolvePackageFullPath(packagePathResolver, name, version);

            var fullPath = Path.Combine(packageFolder, referencePath);

            if (File.Exists(fullPath))
            {
                return(fullPath);
            }

            string message = $@"The requested dependency ({referencePath}) was not found in the global Nuget cache(s).
. Try executing/publishing the script again with the '--no-cache' option";

            throw new InvalidOperationException(message);
        }
        public static void UpdatePackageReferenceMetadata(
            LockFile lockFile,
            FallbackPackagePathResolver pathResolver,
            PackageIdentity package)
        {
            var info = pathResolver.GetPackageInfo(package.Id, package.Version);

            if (info == null)
            {
                // don't do anything if package was not resolved on disk
                return;
            }

            var nuspecFilePath        = info.PathResolver.GetManifestFilePath(package.Id, package.Version);
            var nuspecReader          = new NuspecReader(nuspecFilePath);
            var developmentDependency = nuspecReader.GetDevelopmentDependency();

            if (developmentDependency)
            {
                foreach (var frameworkInfo in lockFile.PackageSpec.TargetFrameworks
                         .OrderBy(framework => framework.FrameworkName.ToString(),
                                  StringComparer.Ordinal))
                {
                    var dependency = frameworkInfo.Dependencies.First(dep => dep.Name.Equals(package.Id, StringComparison.OrdinalIgnoreCase));

                    if (dependency?.SuppressParent == LibraryIncludeFlagUtils.DefaultSuppressParent &&
                        dependency?.IncludeType == LibraryIncludeFlags.All)
                    {
                        var includeType = LibraryIncludeFlags.All & ~LibraryIncludeFlags.Compile;
                        dependency.SuppressParent = LibraryIncludeFlags.All;
                        dependency.IncludeType    = includeType;

                        // update lock file target libraries
                        foreach (var target in lockFile.Targets
                                 .Where(t => EqualityUtility.EqualsWithNullCheck(t.TargetFramework, frameworkInfo.FrameworkName)))
                        {
                            var targetLibrary = target.GetTargetLibrary(package.Id);

                            if (targetLibrary != null)
                            {
                                LockFileUtils.ExcludeItems(targetLibrary, includeType);
                            }
                        }
                    }
                }
            }
        }
Beispiel #28
0
        private string[] GetScriptPaths(FallbackPackagePathResolver packagePathResolver, LockFileTargetLibrary targetLibrary)
        {
            if (targetLibrary.ContentFiles.Count == 0)
            {
                return(Array.Empty <string>());
            }

            var packageFolder = ResolvePackageFullPath(packagePathResolver, targetLibrary.Name, targetLibrary.Version.ToString());

            // Note that we can't use content files directly here since that only works for
            // script packages directly referenced by the script and not script packages having
            // dependencies to other script packages.

            var files = _scriptFilesDependencyResolver.GetScriptFileDependencies(packageFolder);

            return(files);
        }
Beispiel #29
0
        public async Task <bool> ExecuteInitScriptAsync(PackageIdentity identity)
        {
            var result = false;

            // Reserve the key. We can remove if the package has not been restored.
            if (TryMarkVisited(identity, PackageInitPS1State.NotFound))
            {
                var nugetPaths       = NuGetPathContext.Create(Settings);
                var fallbackResolver = new FallbackPackagePathResolver(nugetPaths);
                var installPath      = fallbackResolver.GetPackageDirectory(identity.Id, identity.Version);

                if (!string.IsNullOrEmpty(installPath))
                {
                    var scriptPath = Path.Combine(installPath, "tools", PowerShellScripts.Init);

                    if (File.Exists(scriptPath))
                    {
                        // Init.ps1 is present and will be executed.
                        InitScriptExecutions.TryUpdate(
                            identity,
                            PackageInitPS1State.FoundAndExecuted,
                            PackageInitPS1State.NotFound);

                        var request = new ScriptExecutionRequest(scriptPath, installPath, identity, project: null);

                        await ExecuteScriptCoreAsync(request);

                        result = true;
                    }
                }
                else
                {
                    // Package is not restored. Do not cache the results.
                    PackageInitPS1State dummy;
                    InitScriptExecutions.TryRemove(identity, out dummy);
                    result = false;
                }
            }
            else
            {
                // Key is already present. Simply access its value
                result = (InitScriptExecutions[identity] == PackageInitPS1State.FoundAndExecuted);
            }

            return(result);
        }
        private async Task <(InstalledPackageResultStatus, IReadOnlyCollection <NuGetInstalledPackage>)> GetInstalledPackagesAsync(BuildIntegratedNuGetProject project, CancellationToken cancellationToken)
        {
            NuGetInstalledPackage ToNuGetInstalledPackage(PackageReference packageReference, FallbackPackagePathResolver pathResolver)
            {
                var id = packageReference.PackageIdentity.Id;

                var    versionRange   = packageReference.AllowedVersions;
                string requestedRange =
                    packageReference.AllowedVersions.OriginalString // most packages
                    ?? packageReference.AllowedVersions.ToShortString();
                string version          = versionRange.MinVersion.OriginalVersion ?? versionRange.MinVersion.ToNormalizedString();
                var    installPath      = pathResolver.GetPackageDirectory(id, version);
                bool   directDependency = true;

                return(NuGetContractsFactory.CreateNuGetInstalledPackage(id, requestedRange, version, installPath, directDependency));
            }

            InstalledPackageResultStatus status;
            IReadOnlyCollection <NuGetInstalledPackage> installedPackages;

            var cacheContext = new DependencyGraphCacheContext();

            var(packageSpecs, messages) = await project.GetPackageSpecsAndAdditionalMessagesAsync(cacheContext);

            if (messages?.Any(m => m.Level == LogLevel.Error) == true)
            {
                // Although we know that the project will fail to restore, we may still know about some direct dependencies, so let's return the packages that we know about.
                status = InstalledPackageResultStatus.ProjectInvalid;
            }
            else
            {
                status = InstalledPackageResultStatus.Successful;
            }

            var packageSpec  = packageSpecs.Single(s => s.RestoreMetadata.ProjectStyle == ProjectModel.ProjectStyle.PackageReference || s.RestoreMetadata.ProjectStyle == ProjectModel.ProjectStyle.ProjectJson);
            var packagesPath = VSRestoreSettingsUtilities.GetPackagesPath(_settings, packageSpec);
            FallbackPackagePathResolver pathResolver = new FallbackPackagePathResolver(packagesPath, VSRestoreSettingsUtilities.GetFallbackFolders(_settings, packageSpec));

            var packageReferences = await project.GetInstalledPackagesAsync(cancellationToken);

            installedPackages = packageReferences.Select(p => ToNuGetInstalledPackage(p, pathResolver))
                                .ToList();

            return(status, installedPackages);
        }