Example #1
0
        /// <summary>
        /// Retrieves package paths from provided search paths for installed packages
        /// by name *and* version.
        /// </summary>
        public IEnumerable <PSResourceInfo> GetInstalledPackages(
            IEnumerable <PSResourceInfo> pkgs,
            List <string> pathsToSearch)
        {
            foreach (var pkg in pkgs)
            {
                // Filter on specific version.
                var nugetVersion    = new NuGetVersion(pkg.Version);
                var pkgVersionRange = new VersionRange(
                    minVersion: nugetVersion,
                    includeMinVersion: true,
                    maxVersion: nugetVersion,
                    includeMaxVersion: true);

                // Search by package name.
                var foundPkgPaths = FilterPkgPathsByName(
                    names: new string[] { pkg.Name },
                    pathsToSearch);

                // Filter by package version.
                foreach (var pkgPath in FilterPkgPathsByVersion(
                             versionRange: pkgVersionRange,
                             dirsToSearch: foundPkgPaths,
                             selectPrereleaseOnly: false))
                {
                    PSResourceInfo returnPkg = OutputPackageObject(pkgPath, _scriptDictionary);
                    if (returnPkg != null)
                    {
                        yield return(returnPkg);
                    }
                }
            }
        }
Example #2
0
        private List <PSResourceInfo> FindDependencyPackages(
            PSResourceInfo currentPkg,
            PackageMetadataResource packageMetadataResource,
            SourceCacheContext sourceCacheContext
            )
        {
            List <PSResourceInfo> thoseToAdd = new List <PSResourceInfo>();

            FindDependencyPackagesHelper(currentPkg, thoseToAdd, packageMetadataResource, sourceCacheContext);
            return(thoseToAdd);
        }
Example #3
0
        public IEnumerable <PSResourceInfo> FilterPkgPaths(
            string[] name,
            VersionRange versionRange,
            List <string> pathsToSearch)
        {
            List <string> pgkPathsByName = FilterPkgPathsByName(name, pathsToSearch);

            foreach (string pkgPath in FilterPkgPathsByVersion(versionRange, pgkPathsByName))
            {
                PSResourceInfo pkg = OutputPackageObject(pkgPath, _scriptDictionary);
                if (pkg != null)
                {
                    yield return(pkg);
                }
            }
        }
Example #4
0
        public IEnumerable <PSResourceInfo> GetPackagesFromPath(
            string[] name,
            VersionRange versionRange,
            List <string> pathsToSearch,
            bool selectPrereleaseOnly)
        {
            List <string> pkgPathsByName = FilterPkgPathsByName(name, pathsToSearch);

            foreach (string pkgPath in FilterPkgPathsByVersion(versionRange, pkgPathsByName, selectPrereleaseOnly))
            {
                PSResourceInfo pkg = OutputPackageObject(pkgPath, _scriptDictionary);
                if (pkg != null)
                {
                    yield return(pkg);
                }
            }
        }
Example #5
0
        // Create package object for each found resource directory
        public PSResourceInfo OutputPackageObject(string pkgPath, Dictionary <string, PSResourceInfo> scriptDictionary)
        {
            // If the package path is in the deserialized script dictionary, just return that
            if (scriptDictionary.ContainsKey(pkgPath))
            {
                return(scriptDictionary[pkgPath]);
            }

            // If the pkgName from pkgpath is a script, find the xml file
            string pkgName = Utils.GetInstalledPackageName(pkgPath);
            string xmlFilePath;

            if (File.Exists(pkgPath))
            {
                // Package path is a script file
                xmlFilePath = System.IO.Path.Combine(
                    (new DirectoryInfo(pkgPath).Parent).FullName,
                    "InstalledScriptInfos",
                    $"{pkgName}_InstalledScriptInfo.xml");
            }
            else
            {
                // Otherwise assume it's a module, and look for the xml path that way
                xmlFilePath = System.IO.Path.Combine(pkgPath, "PSGetModuleInfo.xml");
            }

            // Read metadata from XML and parse into PSResourceInfo object
            _cmdletPassedIn.WriteVerbose(string.Format("Reading package metadata from: '{0}'", xmlFilePath));
            if (PSResourceInfo.TryRead(xmlFilePath, out PSResourceInfo psGetInfo, out string errorMsg))
            {
                return(psGetInfo);
            }

            _cmdletPassedIn.WriteVerbose(
                $"Reading metadata for package {pkgName} failed with error: {errorMsg}");
            return(null);
        }
Example #6
0
        // Filter by user provided version
        public IEnumerable <String> FilterPkgPathsByVersion(VersionRange versionRange, List <string> dirsToSearch, bool selectPrereleaseOnly)
        {
            Dbg.Assert(versionRange != null, "Version Range cannot be null");

            // if no version is specified, just get the latest version
            foreach (string pkgPath in dirsToSearch)
            {
                _cmdletPassedIn.WriteVerbose(string.Format("Searching through package path: '{0}'", pkgPath));

                // if this is a module directory
                if (Directory.Exists(pkgPath))
                {
                    // search modules paths
                    // ./Modules/Test-Module/1.0.0
                    // ./Modules/Test-Module/2.0.0
                    _cmdletPassedIn.WriteVerbose(string.Format("Searching through package path: '{0}'", pkgPath));

                    string[] versionsDirs = Utils.GetSubDirectories(pkgPath);

                    if (versionsDirs.Length == 0)
                    {
                        _cmdletPassedIn.WriteVerbose(
                            $"No version subdirectories found for path: {pkgPath}");
                        continue;
                    }

                    // sort and reverse to get package versions in descending order to maintain consistency with V2
                    Array.Sort(versionsDirs);
                    Array.Reverse(versionsDirs);

                    foreach (string versionPath in versionsDirs)
                    {
                        _cmdletPassedIn.WriteVerbose(string.Format("Searching through package version path: '{0}'", versionPath));
                        if (!Utils.GetVersionForInstallPath(installedPkgPath: versionPath,
                                                            isModule: true,
                                                            cmdletPassedIn: _cmdletPassedIn,
                                                            out NuGetVersion pkgNugetVersion))
                        {
                            // skip to next iteration of the loop
                            continue;
                        }

                        _cmdletPassedIn.WriteVerbose(string.Format("Package version parsed as NuGet version: '{0}'", pkgNugetVersion));

                        // For Uninstall-PSResource Prerelease parameter equates to selecting prerelease versions only to uninstall.
                        // For other cmdlets (Find-PSResource, Install-PSResource) Prerelease parmater equates to selecting stable and prerelease versions.
                        // We will not just select prerelase versions. For Get-PSResource, there is no Prerelease parameter.
                        if (versionRange.Satisfies(pkgNugetVersion))
                        {
                            if (!selectPrereleaseOnly || pkgNugetVersion.IsPrerelease)
                            {
                                yield return(versionPath);
                            }
                        }
                    }
                }
                else if (File.Exists(pkgPath))
                {
                    // if it's a script
                    if (versionRange == null || versionRange == VersionRange.All)
                    {
                        // yield results then continue with this iteration of the loop
                        yield return(pkgPath);

                        // We are now done with the current iteration of the for loop because
                        // only one script version can be installed in a particular script path at a time.
                        // if looking for all versions and one was found, then we have found all possible versions at that ./Scripts path
                        // and do not need to parse and check for the version number in the metadata file.
                    }
                    else
                    {
                        // check to make sure it's within the version range.
                        // script versions will be parsed from the script xml file
                        PSResourceInfo scriptInfo = OutputPackageObject(pkgPath, _scriptDictionary);
                        if (!Utils.GetVersionForInstallPath(installedPkgPath: pkgPath,
                                                            isModule: false,
                                                            cmdletPassedIn: _cmdletPassedIn,
                                                            out NuGetVersion pkgNugetVersion))
                        {
                            // skip to next iteration of the loop
                            yield return(pkgPath);
                        }

                        _cmdletPassedIn.WriteVerbose(string.Format("Package version parsed as NuGet version: '{0}'", pkgNugetVersion));
                        if (versionRange.Satisfies(pkgNugetVersion))
                        {
                            _scriptDictionary.Add(pkgPath, scriptInfo);
                            yield return(pkgPath);
                        }
                    }
                }
            }
        }
Example #7
0
        private void MoveFilesIntoInstallPath(
            PSResourceInfo pkgInfo,
            bool isModule,
            bool isLocalRepo,
            string dirNameVersion,
            string tempInstallPath,
            string installPath,
            string newVersion,
            string moduleManifestVersion,
            string scriptPath)
        {
            // Creating the proper installation path depending on whether pkg is a module or script
            var newPathParent         = isModule ? Path.Combine(installPath, pkgInfo.Name) : installPath;
            var finalModuleVersionDir = isModule ? Path.Combine(installPath, pkgInfo.Name, moduleManifestVersion) : installPath;

            // If script, just move the files over, if module, move the version directory over
            var tempModuleVersionDir = (!isModule || isLocalRepo) ? dirNameVersion
                : Path.Combine(tempInstallPath, pkgInfo.Name.ToLower(), newVersion);

            _cmdletPassedIn.WriteVerbose(string.Format("Installation source path is: '{0}'", tempModuleVersionDir));
            _cmdletPassedIn.WriteVerbose(string.Format("Installation destination path is: '{0}'", finalModuleVersionDir));

            if (isModule)
            {
                // If new path does not exist
                if (!Directory.Exists(newPathParent))
                {
                    _cmdletPassedIn.WriteVerbose(string.Format("Attempting to move '{0}' to '{1}'", tempModuleVersionDir, finalModuleVersionDir));
                    Directory.CreateDirectory(newPathParent);
                    Utils.MoveDirectory(tempModuleVersionDir, finalModuleVersionDir);
                }
                else
                {
                    _cmdletPassedIn.WriteVerbose(string.Format("Temporary module version directory is: '{0}'", tempModuleVersionDir));

                    if (Directory.Exists(finalModuleVersionDir))
                    {
                        // Delete the directory path before replacing it with the new module.
                        // If deletion fails (usually due to binary file in use), then attempt restore so that the currently
                        // installed module is not corrupted.
                        _cmdletPassedIn.WriteVerbose(string.Format("Attempting to delete with restore on failure.'{0}'", finalModuleVersionDir));
                        Utils.DeleteDirectoryWithRestore(finalModuleVersionDir);
                    }

                    _cmdletPassedIn.WriteVerbose(string.Format("Attempting to move '{0}' to '{1}'", tempModuleVersionDir, finalModuleVersionDir));
                    Utils.MoveDirectory(tempModuleVersionDir, finalModuleVersionDir);
                }
            }
            else
            {
                if (!_savePkg)
                {
                    // Need to delete old xml files because there can only be 1 per script
                    var scriptXML = pkgInfo.Name + "_InstalledScriptInfo.xml";
                    _cmdletPassedIn.WriteVerbose(string.Format("Checking if path '{0}' exists: ", File.Exists(Path.Combine(installPath, "InstalledScriptInfos", scriptXML))));
                    if (File.Exists(Path.Combine(installPath, "InstalledScriptInfos", scriptXML)))
                    {
                        _cmdletPassedIn.WriteVerbose(string.Format("Deleting script metadata XML"));
                        File.Delete(Path.Combine(installPath, "InstalledScriptInfos", scriptXML));
                    }

                    _cmdletPassedIn.WriteVerbose(string.Format("Moving '{0}' to '{1}'", Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, "InstalledScriptInfos", scriptXML)));
                    Utils.MoveFiles(Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, "InstalledScriptInfos", scriptXML));

                    // Need to delete old script file, if that exists
                    _cmdletPassedIn.WriteVerbose(string.Format("Checking if path '{0}' exists: ", File.Exists(Path.Combine(finalModuleVersionDir, pkgInfo.Name + ".ps1"))));
                    if (File.Exists(Path.Combine(finalModuleVersionDir, pkgInfo.Name + ".ps1")))
                    {
                        _cmdletPassedIn.WriteVerbose(string.Format("Deleting script file"));
                        File.Delete(Path.Combine(finalModuleVersionDir, pkgInfo.Name + ".ps1"));
                    }
                }

                _cmdletPassedIn.WriteVerbose(string.Format("Moving '{0}' to '{1}'", scriptPath, Path.Combine(finalModuleVersionDir, pkgInfo.Name + ".ps1")));
                Utils.MoveFiles(scriptPath, Path.Combine(finalModuleVersionDir, pkgInfo.Name + ".ps1"));
            }
        }
Example #8
0
        private void CreateMetadataXMLFile(string dirNameVersion, string installPath, PSResourceInfo pkg, bool isModule)
        {
            // Script will have a metadata file similar to:  "TestScript_InstalledScriptInfo.xml"
            // Modules will have the metadata file: "PSGetModuleInfo.xml"
            var metadataXMLPath = isModule ? Path.Combine(dirNameVersion, "PSGetModuleInfo.xml")
                : Path.Combine(dirNameVersion, (pkg.Name + "_InstalledScriptInfo.xml"));

            pkg.InstalledDate     = DateTime.Now;
            pkg.InstalledLocation = installPath;

            // Write all metadata into metadataXMLPath
            if (!pkg.TryWrite(metadataXMLPath, out string error))
            {
                var message = string.Format("{0} package could not be installed with error: Error parsing metadata into XML: '{1}'", pkg.Name, error);
                var ex      = new ArgumentException(message);
                var ErrorParsingMetadata = new ErrorRecord(ex, "ErrorParsingMetadata", ErrorCategory.ParserError, null);

                _cmdletPassedIn.WriteError(ErrorParsingMetadata);
                _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase));
            }
        }
Example #9
0
        private bool CallAcceptLicense(PSResourceInfo p, string moduleManifest, string tempInstallPath, string newVersion)
        {
            var requireLicenseAcceptance = false;
            var success = true;

            if (File.Exists(moduleManifest))
            {
                using (StreamReader sr = new StreamReader(moduleManifest))
                {
                    var text = sr.ReadToEnd();

                    var pattern        = "RequireLicenseAcceptance\\s*=\\s*\\$true";
                    var patternToSkip1 = "#\\s*RequireLicenseAcceptance\\s*=\\s*\\$true";
                    var patternToSkip2 = "\\*\\s*RequireLicenseAcceptance\\s*=\\s*\\$true";

                    Regex rgx         = new Regex(pattern);
                    Regex rgxComment1 = new Regex(patternToSkip1);
                    Regex rgxComment2 = new Regex(patternToSkip2);
                    if (rgx.IsMatch(text) && !rgxComment1.IsMatch(text) && !rgxComment2.IsMatch(text))
                    {
                        requireLicenseAcceptance = true;
                    }
                }

                // Licesnse agreement processing
                if (requireLicenseAcceptance)
                {
                    // If module requires license acceptance and -AcceptLicense is not passed in, display prompt
                    if (!_acceptLicense)
                    {
                        var PkgTempInstallPath = Path.Combine(tempInstallPath, p.Name, newVersion);
                        var LicenseFilePath    = Path.Combine(PkgTempInstallPath, "License.txt");

                        if (!File.Exists(LicenseFilePath))
                        {
                            var exMessage          = String.Format("{0} package could not be installed with error: License.txt not found. License.txt must be provided when user license acceptance is required.", p.Name);
                            var ex                 = new ArgumentException(exMessage);
                            var acceptLicenseError = new ErrorRecord(ex, "LicenseTxtNotFound", ErrorCategory.ObjectNotFound, null);

                            _cmdletPassedIn.WriteError(acceptLicenseError);
                            _pkgNamesToInstall.RemoveAll(x => x.Equals(p.Name, StringComparison.InvariantCultureIgnoreCase));
                            success = false;
                        }

                        // Otherwise read LicenseFile
                        string licenseText            = System.IO.File.ReadAllText(LicenseFilePath);
                        var    acceptanceLicenseQuery = $"Do you accept the license terms for module '{p.Name}'.";
                        var    message = licenseText + "`r`n" + acceptanceLicenseQuery;

                        var title                = "License Acceptance";
                        var yesToAll             = false;
                        var noToAll              = false;
                        var shouldContinueResult = _cmdletPassedIn.ShouldContinue(message, title, true, ref yesToAll, ref noToAll);

                        if (shouldContinueResult || yesToAll)
                        {
                            _acceptLicense = true;
                        }
                    }

                    // Check if user agreed to license terms, if they didn't then throw error, otherwise continue to install
                    if (!_acceptLicense)
                    {
                        var message            = String.Format("{0} package could not be installed with error: License Acceptance is required for module '{0}'. Please specify '-AcceptLicense' to perform this operation.", p.Name);
                        var ex                 = new ArgumentException(message);
                        var acceptLicenseError = new ErrorRecord(ex, "ForceAcceptLicense", ErrorCategory.InvalidArgument, null);

                        _cmdletPassedIn.WriteError(acceptLicenseError);
                        _pkgNamesToInstall.RemoveAll(x => x.Equals(p.Name, StringComparison.InvariantCultureIgnoreCase));
                        success = false;
                    }
                }
            }

            return(success);
        }
Example #10
0
        private void MoveFilesIntoInstallPath(PSResourceInfo p, bool isScript, bool isLocalRepo, string dirNameVersion, string tempInstallPath, string installPath, string newVersion, string moduleManifestVersion, string nupkgVersion, string versionWithoutPrereleaseTag, string scriptPath)
        {
            // Creating the proper installation path depending on whether pkg is a module or script
            var newPathParent         = isScript ? installPath : Path.Combine(installPath, p.Name);
            var finalModuleVersionDir = isScript ? installPath : Path.Combine(installPath, p.Name, moduleManifestVersion);  // versionWithoutPrereleaseTag

            _cmdletPassedIn.WriteDebug(string.Format("Installation path is: '{0}'", finalModuleVersionDir));

            // If script, just move the files over, if module, move the version directory over
            var tempModuleVersionDir = (isScript || isLocalRepo) ? dirNameVersion
                : Path.Combine(tempInstallPath, p.Name.ToLower(), newVersion);

            _cmdletPassedIn.WriteVerbose(string.Format("Full installation path is: '{0}'", tempModuleVersionDir));

            if (isScript)
            {
                if (!_savePkg)
                {
                    // Need to delete old xml files because there can only be 1 per script
                    var scriptXML = p.Name + "_InstalledScriptInfo.xml";
                    _cmdletPassedIn.WriteDebug(string.Format("Checking if path '{0}' exists: ", File.Exists(Path.Combine(installPath, "InstalledScriptInfos", scriptXML))));
                    if (File.Exists(Path.Combine(installPath, "InstalledScriptInfos", scriptXML)))
                    {
                        _cmdletPassedIn.WriteDebug(string.Format("Deleting script metadata XML"));
                        File.Delete(Path.Combine(installPath, "InstalledScriptInfos", scriptXML));
                    }

                    _cmdletPassedIn.WriteDebug(string.Format("Moving '{0}' to '{1}'", Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, "InstalledScriptInfos", scriptXML)));
                    Utils.MoveFiles(Path.Combine(dirNameVersion, scriptXML), Path.Combine(installPath, "InstalledScriptInfos", scriptXML));

                    // Need to delete old script file, if that exists
                    _cmdletPassedIn.WriteDebug(string.Format("Checking if path '{0}' exists: ", File.Exists(Path.Combine(finalModuleVersionDir, p.Name + ".ps1"))));
                    if (File.Exists(Path.Combine(finalModuleVersionDir, p.Name + ".ps1")))
                    {
                        _cmdletPassedIn.WriteDebug(string.Format("Deleting script file"));
                        File.Delete(Path.Combine(finalModuleVersionDir, p.Name + ".ps1"));
                    }
                }

                _cmdletPassedIn.WriteDebug(string.Format("Moving '{0}' to '{1}'", scriptPath, Path.Combine(finalModuleVersionDir, p.Name + ".ps1")));
                Utils.MoveFiles(scriptPath, Path.Combine(finalModuleVersionDir, p.Name + ".ps1"));
            }
            else
            {
                // If new path does not exist
                if (!Directory.Exists(newPathParent))
                {
                    _cmdletPassedIn.WriteDebug(string.Format("Attempting to move '{0}' to '{1}'", tempModuleVersionDir, finalModuleVersionDir));
                    Directory.CreateDirectory(newPathParent);
                    Utils.MoveDirectory(tempModuleVersionDir, finalModuleVersionDir);
                }
                else
                {
                    _cmdletPassedIn.WriteDebug(string.Format("Temporary module version directory is: '{0}'", tempModuleVersionDir));

                    // At this point if
                    if (Directory.Exists(finalModuleVersionDir))
                    {
                        // Delete the directory path before replacing it with the new module
                        _cmdletPassedIn.WriteDebug(string.Format("Attempting to delete '{0}'", finalModuleVersionDir));
                        Directory.Delete(finalModuleVersionDir, true);
                    }

                    _cmdletPassedIn.WriteDebug(string.Format("Attempting to move '{0}' to '{1}'", tempModuleVersionDir, finalModuleVersionDir));
                    Utils.MoveDirectory(tempModuleVersionDir, finalModuleVersionDir);
                }
            }
        }
Example #11
0
        private void CreateMetadataXMLFile(string dirNameVersion, string installPath, string repoName, PSResourceInfo pkg, bool isScript)
        {
            // Script will have a metadata file similar to:  "TestScript_InstalledScriptInfo.xml"
            // Modules will have the metadata file: "PSGetModuleInfo.xml"
            var metadataXMLPath = isScript ? Path.Combine(dirNameVersion, (pkg.Name + "_InstalledScriptInfo.xml"))
                : Path.Combine(dirNameVersion, "PSGetModuleInfo.xml");

            pkg.InstalledDate     = DateTime.Now;
            pkg.InstalledLocation = installPath;

            // Write all metadata into metadataXMLPath
            if (!pkg.TryWrite(metadataXMLPath, out string error))
            {
                var message = string.Format("Error parsing metadata into XML: '{0}'", error);
                var ex      = new ArgumentException(message);
                var ErrorParsingMetadata = new ErrorRecord(ex, "ErrorParsingMetadata", ErrorCategory.ParserError, null);
                WriteError(ErrorParsingMetadata);
            }
        }
Example #12
0
        private void FindDependencyPackagesHelper(
            PSResourceInfo currentPkg,
            List <PSResourceInfo> thoseToAdd,
            PackageMetadataResource packageMetadataResource,
            SourceCacheContext sourceCacheContext
            )
        {
            foreach (var dep in currentPkg.Dependencies)
            {
                IEnumerable <IPackageSearchMetadata> depPkgs = packageMetadataResource.GetMetadataAsync(
                    packageId: dep.Name,
                    includePrerelease: _prerelease,
                    includeUnlisted: false,
                    sourceCacheContext: sourceCacheContext,
                    log: NullLogger.Instance,
                    token: _cancellationToken).GetAwaiter().GetResult();

                if (depPkgs.Count() > 0)
                {
                    if (dep.VersionRange == VersionRange.All)
                    {
                        // return latest version
                        IPackageSearchMetadata depPkgLatestVersion = depPkgs.First();

                        if (!PSResourceInfo.TryConvert(
                                metadataToParse: depPkgLatestVersion,
                                psGetInfo: out PSResourceInfo depPSResourceInfoPkg,
                                repositoryName: currentPkg.Repository,
                                type: currentPkg.Type,
                                errorMsg: out string errorMsg))
                        {
                            _cmdletPassedIn.WriteError(new ErrorRecord(
                                                           new PSInvalidOperationException("Error parsing dependency IPackageSearchMetadata to PSResourceInfo with message: " + errorMsg),
                                                           "DependencyIPackageSearchMetadataToPSResourceInfoParsingError",
                                                           ErrorCategory.InvalidResult,
                                                           this));
                        }

                        thoseToAdd.Add(depPSResourceInfoPkg);
                        FindDependencyPackagesHelper(depPSResourceInfoPkg, thoseToAdd, packageMetadataResource, sourceCacheContext);
                    }
                    else
                    {
                        List <IPackageSearchMetadata> pkgVersionsInRange = depPkgs.Where(
                            p => dep.VersionRange.Satisfies(
                                p.Identity.Version, VersionComparer.VersionRelease)).OrderByDescending(
                            p => p.Identity.Version).ToList();

                        if (pkgVersionsInRange.Count() > 0)
                        {
                            IPackageSearchMetadata depPkgLatestInRange = pkgVersionsInRange.First();
                            if (depPkgLatestInRange != null)
                            {
                                if (!PSResourceInfo.TryConvert(
                                        metadataToParse: depPkgLatestInRange,
                                        psGetInfo: out PSResourceInfo depPSResourceInfoPkg,
                                        repositoryName: currentPkg.Repository,
                                        type: currentPkg.Type,
                                        errorMsg: out string errorMsg))
                                {
                                    _cmdletPassedIn.WriteError(new ErrorRecord(
                                                                   new PSInvalidOperationException("Error parsing dependency range IPackageSearchMetadata to PSResourceInfo with message: " + errorMsg),
                                                                   "DependencyRangeIPackageSearchMetadataToPSResourceInfoParsingError",
                                                                   ErrorCategory.InvalidResult,
                                                                   this));
                                }

                                thoseToAdd.Add(depPSResourceInfoPkg);
                                FindDependencyPackagesHelper(depPSResourceInfoPkg, thoseToAdd, packageMetadataResource, sourceCacheContext);
                            }
                        }
                    }
                }
            }
        }
Example #13
0
 private bool IsTagMatch(PSResourceInfo pkg)
 {
     return(_tag.Intersect(pkg.Tags, StringComparer.InvariantCultureIgnoreCase).ToList().Count > 0);
 }
Example #14
0
        // Filter by user provided version
        public IEnumerable <String> FilterPkgPathsByVersion(VersionRange versionRange, List <string> dirsToSearch)
        {
            Dbg.Assert(versionRange != null, "Version Range cannot be null");

            // if no version is specified, just get the latest version
            foreach (string pkgPath in dirsToSearch)
            {
                _cmdletPassedIn.WriteDebug(string.Format("Searching through package path: '{0}'", pkgPath));

                // if this is a module directory
                if (Directory.Exists(pkgPath))
                {
                    // search modules paths
                    // ./Modules/Test-Module/1.0.0
                    // ./Modules/Test-Module/2.0.0
                    _cmdletPassedIn.WriteDebug(string.Format("Searching through package path: '{0}'", pkgPath));

                    string[] versionsDirs = Utils.GetSubDirectories(pkgPath);

                    if (versionsDirs.Length == 0)
                    {
                        _cmdletPassedIn.WriteVerbose(
                            $"No version subdirectories found for path: {pkgPath}");
                        continue;
                    }

                    // sort and reverse to get package versions in descending order to maintain consistency with V2
                    Array.Sort(versionsDirs);
                    Array.Reverse(versionsDirs);

                    foreach (string versionPath in versionsDirs)
                    {
                        _cmdletPassedIn.WriteDebug(string.Format("Searching through package version path: '{0}'", versionPath));
                        DirectoryInfo dirInfo = new DirectoryInfo(versionPath);

                        // if the version is not valid, we'll just skip it and output a debug message
                        if (!NuGetVersion.TryParse(dirInfo.Name, out NuGetVersion dirAsNugetVersion))
                        {
                            _cmdletPassedIn.WriteVerbose(string.Format("Leaf directory in path '{0}' cannot be parsed into a version.", versionPath));

                            // skip to next iteration of the loop
                            continue;
                        }
                        _cmdletPassedIn.WriteVerbose(string.Format("Directory parsed as NuGet version: '{0}'", dirAsNugetVersion));

                        if (versionRange.Satisfies(dirAsNugetVersion))
                        {
                            // This will be one version or a version range.
                            // yield results then continue with this iteration of the loop
                            yield return(versionPath);
                        }
                    }
                }
                else if (File.Exists(pkgPath))
                {
                    // if it's a script
                    if (versionRange == null || versionRange == VersionRange.All)
                    {
                        // yield results then continue with this iteration of the loop
                        yield return(pkgPath);

                        // We are now done with the current iteration of the for loop because
                        // only one script version can be installed in a particular script path at a time.
                        // if looking for all versions and one was found, then we have found all possible versions at that ./Scripts path
                        // and do not need to parse and check for the version number in the metadata file.
                    }
                    else
                    {
                        // check to make sure it's within the version range.
                        // script versions will be parsed from the script xml file
                        PSResourceInfo scriptInfo = OutputPackageObject(pkgPath, _scriptDictionary);
                        if (scriptInfo == null)
                        {
                            // if script was not found skip to the next iteration of the loop
                            continue;
                        }

                        if (!NuGetVersion.TryParse(scriptInfo.Version.ToString(), out NuGetVersion scriptVersion))
                        {
                            _cmdletPassedIn.WriteVerbose(string.Format("Version '{0}' could not be properly parsed from the script metadata file from the script installed at '{1}'", scriptInfo.Version.ToString(), scriptInfo.InstalledLocation));
                        }
                        else if (versionRange.Satisfies(scriptVersion))
                        {
                            _scriptDictionary.Add(pkgPath, scriptInfo);
                            yield return(pkgPath);
                        }
                    }
                }
            }
        }