예제 #1
0
        public virtual void TestIsEqual()
        {
            VersionRange range1 = VersionRange.Parse("[1.1.0.1,1.1.0.3)");
            VersionRange range2 = VersionRange.Parse(range1.ToString());

            Assert.IsTrue(range1.Equals(range2));
        }
예제 #2
0
        public void WriteJson_WritesStrictVersionRangeToString()
        {
            using (var stringWriter = new StringWriter())
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    _converter.WriteJson(jsonWriter, _strictVersionRange, JsonSerializationUtilities.Serializer);

                    Assert.Equal($"\"{_strictVersionRange.ToString()}\"", stringWriter.ToString());
                }
        }
예제 #3
0
        public void WriteJson_WritesWildCardVersionRangeToString()
        {
            var versionRange = new VersionRange(null, true, null, true, new FloatRange(NuGetVersionFloatBehavior.Major), originalString: "*");

            using (var stringWriter = new StringWriter())
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    _converter.WriteJson(jsonWriter, versionRange, JsonSerializationUtilities.Serializer);

                    Assert.Equal($"\"{versionRange.ToString()}\"", stringWriter.ToString());
                }
        }
예제 #4
0
        public void ParseVersionRangeToStringReParse(NuGetVersion min, NuGetVersion max, bool minInc, bool maxInc)
        {
            // Act
            var original    = new VersionRange(min, minInc, max, maxInc);
            var versionInfo = VersionRange.Parse(original.ToString());

            // Assert
            Assert.Equal(min, versionInfo.MinVersion, VersionComparer.Default);
            Assert.Equal(max, versionInfo.MaxVersion, VersionComparer.Default);
            Assert.Equal(minInc, versionInfo.IsMinInclusive);
            Assert.Equal(maxInc, versionInfo.IsMaxInclusive);
        }
예제 #5
0
        private FilePath CreateTempProject(
            PackageId packageId,
            VersionRange versionRange,
            string targetFramework,
            DirectoryPath?restoreDirectory,
            DirectoryPath assetJsonOutputDirectory,
            DirectoryPath?rootConfigDirectory,
            string[] additionalFeeds)
        {
            var tempProject = _tempProject ?? new DirectoryPath(Path.GetTempPath())
                              .WithSubDirectories(Path.GetRandomFileName())
                              .WithFile("restore.csproj");

            if (Path.GetExtension(tempProject.Value) != "csproj")
            {
                tempProject = new FilePath(Path.ChangeExtension(tempProject.Value, "csproj"));
            }

            Directory.CreateDirectory(tempProject.GetDirectoryPath().Value);

            var tempProjectContent = new XDocument(
                new XElement("Project",
                             new XElement("PropertyGroup",
                                                                                                                         // due to https://github.com/Microsoft/msbuild/issues/1603 -- import SDK after setting MsBuildProjectExtensionsPath
                                          new XElement("MsBuildProjectExtensionsPath", assetJsonOutputDirectory.Value)), // change the output directory of asset.json
                             new XElement(("Import"),
                                          new XAttribute("Project", "Sdk.props"),
                                          new XAttribute("Sdk", "Microsoft.NET.Sdk")),
                             new XElement("PropertyGroup",
                                          new XElement("TargetFramework", targetFramework),
                                          restoreDirectory.HasValue ? new XElement("RestorePackagesPath", restoreDirectory.Value.Value) : null,
                                          new XElement("RestoreProjectStyle", "DotnetToolReference"),                                                // without it, project cannot reference tool package
                                          new XElement("RestoreRootConfigDirectory", rootConfigDirectory?.Value ?? Directory.GetCurrentDirectory()), // config file probing start directory
                                          new XElement("DisableImplicitFrameworkReferences", "true"),                                                // no Microsoft.NETCore.App in tool folder
                                          new XElement("RestoreFallbackFolders", "clear"),                                                           // do not use fallbackfolder, tool package need to be copied to tool folder
                                          new XElement("RestoreAdditionalProjectSources", JoinSourceAndOfflineCache(additionalFeeds)),
                                          new XElement("RestoreAdditionalProjectFallbackFolders", string.Empty),                                     // block other
                                          new XElement("RestoreAdditionalProjectFallbackFoldersExcludes", string.Empty),                             // block other
                                          new XElement("DisableImplicitNuGetFallbackFolder", "true")),                                               // disable SDK side implicit NuGetFallbackFolder
                             new XElement("ItemGroup",
                                          new XElement("PackageReference",
                                                       new XAttribute("Include", packageId.ToString()),
                                                       new XAttribute("Version",
                                                                      versionRange?.ToString("N", new VersionRangeFormatter()) ?? "*"))), // nuget will restore latest stable for * and format N is the normalization format
                             new XElement(("Import"),
                                          new XAttribute("Project", "Sdk.targets"),
                                          new XAttribute("Sdk", "Microsoft.NET.Sdk"))));

            File.WriteAllText(tempProject.Value, tempProjectContent.ToString());
            return(tempProject);
        }
예제 #6
0
        public override string ToString()
        {
            var output = Name;

            if (VersionRange != null)
            {
                output += " " + VersionRange.ToString();
            }
            if (!string.IsNullOrEmpty(TypeConstraint))
            {
                output = TypeConstraint + "/" + output;
            }
            return(output);
        }
예제 #7
0
        private FilePath CreateTempProject(
            PackageId packageId,
            VersionRange versionRange,
            string targetFramework,
            DirectoryPath restoreDirectory,
            DirectoryPath?rootConfigDirectory)
        {
            var tempProject = _tempProject ?? new DirectoryPath(Path.GetTempPath())
                              .WithSubDirectories(Path.GetRandomFileName())
                              .WithFile("restore.csproj");

            if (Path.GetExtension(tempProject.Value) != "csproj")
            {
                tempProject = new FilePath(Path.ChangeExtension(tempProject.Value, "csproj"));
            }

            Directory.CreateDirectory(tempProject.GetDirectoryPath().Value);

            var tempProjectContent = new XDocument(
                new XElement("Project",
                             new XAttribute("Sdk", "Microsoft.NET.Sdk"),
                             new XElement("PropertyGroup",
                                          new XElement("TargetFramework", targetFramework),
                                          new XElement("RestorePackagesPath", restoreDirectory.Value),
                                          new XElement("RestoreProjectStyle", "DotnetToolReference"),                                                // without it, project cannot reference tool package
                                          new XElement("RestoreRootConfigDirectory", rootConfigDirectory?.Value ?? Directory.GetCurrentDirectory()), // config file probing start directory
                                          new XElement("DisableImplicitFrameworkReferences", "true"),                                                // no Microsoft.NETCore.App in tool folder
                                          new XElement("RestoreFallbackFolders", "clear"),                                                           // do not use fallbackfolder, tool package need to be copied to tool folder
                                          new XElement("RestoreAdditionalProjectSources",                                                            // use fallbackfolder as feed to enable offline
                                                       Directory.Exists(_offlineFeed.Value) ? _offlineFeed.Value : string.Empty),
                                          new XElement("RestoreAdditionalProjectFallbackFolders", string.Empty),                                     // block other
                                          new XElement("RestoreAdditionalProjectFallbackFoldersExcludes", string.Empty),                             // block other
                                          new XElement("DisableImplicitNuGetFallbackFolder", "true")),                                               // disable SDK side implicit NuGetFallbackFolder
                             new XElement("ItemGroup",
                                          new XElement("PackageReference",
                                                       new XAttribute("Include", packageId.ToString()),
                                                       new XAttribute("Version",
                                                                      versionRange?.ToString("S", new VersionRangeFormatter()) ?? "*") // nuget will restore latest stable for *
                                                       ))
                             ));

            File.WriteAllText(tempProject.Value, tempProjectContent.ToString());
            return(tempProject);
        }
예제 #8
0
        private void RewriteRuntimeJsonVersions(JObject content)
        {
            var versionProperties = content
                                    .Descendants()
                                    .OfType <JProperty>()
                                    .Where(p =>
                                           p.Value is JValue v &&
                                           v.Type == JTokenType.String);

            foreach (var p in versionProperties)
            {
                var range = VersionRange.Parse(p.Value.Value <string>());

                if (range.MinVersion.OriginalVersion == OriginalVersion)
                {
                    var newRange = new VersionRange(
                        NuGetVersion.Parse(TargetVersion),
                        range.Float);

                    p.Value = newRange.ToString();
                }
            }
        }
예제 #9
0
 public override string ToString() => VersionRange.ToString();
예제 #10
0
 public override void WriteJson(JsonWriter writer, VersionRange?value, JsonSerializer serializer)
 {
     writer.WriteValue(value?.ToString());
 }
예제 #11
0
파일: LibraryRange.cs 프로젝트: sanbir/dnx
        public override string ToString()
        {
            var name = IsGacOrFrameworkReference ? "framework/" + Name : Name;

            return(name + " " + (VersionRange?.ToString()));
        }
예제 #12
0
        public void ParseVersionRangeToStringReParse(string minString, string maxString, bool minInc, bool maxInc)
        {
            // Arrange
            var min = NuGetVersion.Parse(minString);
            var max = NuGetVersion.Parse(maxString);

            // Act
            var original = new VersionRange(min, minInc, max, maxInc);
            var versionInfo = VersionRange.Parse(original.ToString());

            // Assert
            Assert.Equal(min, versionInfo.MinVersion, VersionComparer.Default);
            Assert.Equal(max, versionInfo.MaxVersion, VersionComparer.Default);
            Assert.Equal(minInc, versionInfo.IsMinInclusive);
            Assert.Equal(maxInc, versionInfo.IsMaxInclusive);
        }
예제 #13
0
        public List <PSObject> ProcessGetParams(string[] name, string version, bool prerelease, string path)
        {
            var dirsToSearch = new List <string>();

            if (path != null)
            {
                cmdletPassedIn.WriteDebug(string.Format("Provided path is: '{0}'", path));
                dirsToSearch.AddRange(Directory.GetDirectories(path).ToList());
            }
            else
            {
                // PSModules path
                var psModulePath = Environment.GetEnvironmentVariable("PSModulePath");
                var modulePaths  = psModulePath.Split(';');


#if NET472
                programFilesPath = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.ProgramFiles), "WindowsPowerShell");
                myDocumentsPath  = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.MyDocuments), "WindowsPowerShell");
#else
                // If PS6+ on Windows
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    myDocumentsPath  = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.MyDocuments), "PowerShell");
                    programFilesPath = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.ProgramFiles), "PowerShell");
                }
                else
                {
                    // Paths are the same for both Linux and MacOS
                    myDocumentsPath  = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.LocalApplicationData), "powershell");
                    programFilesPath = System.IO.Path.Combine("/usr", "local", "share", "powershell");
                }
#endif
                cmdletPassedIn.WriteDebug(string.Format("Current user scope path: '{0}'", myDocumentsPath));
                cmdletPassedIn.WriteDebug(string.Format("All users scope path: '{0}'", programFilesPath));

                /*** Will search first in PSModulePath, then will search in default paths ***/

                foreach (var modulePath in modulePaths)
                {
                    dirsToSearch.AddRange(Directory.GetDirectories(modulePath).ToList());
                }


                var pfModulesPath = System.IO.Path.Combine(programFilesPath, "Modules");
                if (Directory.Exists(pfModulesPath))
                {
                    dirsToSearch.AddRange(Directory.GetDirectories(pfModulesPath).ToList());
                }

                var mdModulesPath = System.IO.Path.Combine(myDocumentsPath, "Modules");
                if (Directory.Exists(mdModulesPath))
                {
                    dirsToSearch.AddRange(Directory.GetDirectories(mdModulesPath).ToList());
                }


                var pfScriptsPath = System.IO.Path.Combine(programFilesPath, "Scripts", "InstalledScriptInfos");
                if (Directory.Exists(pfScriptsPath))
                {
                    dirsToSearch.AddRange(Directory.GetFiles(pfScriptsPath).ToList());
                }

                var mdScriptsPath = System.IO.Path.Combine(myDocumentsPath, "Scripts", "InstalledScriptInfos");
                if (Directory.Exists(mdScriptsPath))
                {
                    dirsToSearch.AddRange(Directory.GetFiles(mdScriptsPath).ToList());
                }


                // uniqueify
                dirsToSearch = dirsToSearch.Distinct().ToList();
            }

            foreach (var dir in dirsToSearch)
            {
                cmdletPassedIn.WriteDebug(string.Format("All directories to search: '{0}'", dir));
            }

            // Or a list of the passed in names
            if (name != null && !name[0].Equals("*"))
            {
                var nameLowerCased = new List <string>();
                var scriptXMLnames = new List <string>();
                Array.ForEach(name, n => nameLowerCased.Add(n.ToLower()));
                Array.ForEach(name, n => scriptXMLnames.Add((n + "_InstalledScriptInfo.xml").ToLower()));

                dirsToSearch = dirsToSearch.FindAll(p => (nameLowerCased.Contains(new DirectoryInfo(p).Name.ToLower()) ||
                                                          scriptXMLnames.Contains((System.IO.Path.GetFileName(p)).ToLower())));

                cmdletPassedIn.WriteDebug(dirsToSearch.Any().ToString());
            }

            // try to parse into a specific NuGet version
            VersionRange versionRange = null;
            if (version != null)
            {
                NuGetVersion specificVersion;
                NuGetVersion.TryParse(version, out specificVersion);

                if (specificVersion != null)
                {
                    // exact version
                    versionRange = new VersionRange(specificVersion, true, specificVersion, true, null, null);
                    cmdletPassedIn.WriteDebug(string.Format("A specific version, '{0}', is specified", versionRange.ToString()));
                }
                else
                {
                    // check if version range
                    versionRange = VersionRange.Parse(version);
                    cmdletPassedIn.WriteDebug(string.Format("A version range, '{0}', is specified", versionRange.ToString()));
                }
            }

            List <string> installedPkgsToReturn = new List <string>();

            IEnumerable <string> returnPkgs = null;

            //2) use above list to check
            // if the version specificed is a version range
            if (versionRange != null)
            {
                foreach (var pkgPath in dirsToSearch)
                {
                    cmdletPassedIn.WriteDebug(string.Format("Searching through package path: '{0}'", pkgPath));
                    var versionsDirs = Directory.GetDirectories(pkgPath);

                    foreach (var versionPath in versionsDirs)
                    {
                        cmdletPassedIn.WriteDebug(string.Format("Searching through package version path: '{0}'", versionPath));
                        NuGetVersion dirAsNugetVersion;
                        var          dirInfo = new DirectoryInfo(versionPath);
                        NuGetVersion.TryParse(dirInfo.Name, out dirAsNugetVersion);
                        cmdletPassedIn.WriteDebug(string.Format("Directory parsed as NuGet version: '{0}'", dirAsNugetVersion));

                        if (versionRange.Satisfies(dirAsNugetVersion))
                        {
                            // just search scripts paths
                            if (pkgPath.ToLower().Contains("Scripts"))
                            {
                                if (File.Exists(pkgPath))
                                {
                                    installedPkgsToReturn.Add(pkgPath);
                                }
                            }
                            else
                            {
                                // modules paths
                                versionsDirs = Directory.GetDirectories(pkgPath);
                                cmdletPassedIn.WriteDebug(string.Format("Getting sub directories from : '{0}'", pkgPath));

                                // Check if the pkg path actually has version sub directories.
                                if (versionsDirs.Length != 0)
                                {
                                    Array.Sort(versionsDirs, StringComparer.OrdinalIgnoreCase);
                                    Array.Reverse(versionsDirs);

                                    var pkgXmlFilePath = System.IO.Path.Combine(versionsDirs.First(), "PSGetModuleInfo.xml");

                                    // TODO:  check if this xml file exists, if it doesn't check if it exists in a previous version
                                    cmdletPassedIn.WriteDebug(string.Format("Found module XML: '{0}'", pkgXmlFilePath));

                                    installedPkgsToReturn.Add(pkgXmlFilePath);
                                }
                            }

                            installedPkgsToReturn.Add(versionPath);
                        }
                    }
                }
            }
            else
            {
                cmdletPassedIn.WriteDebug("No version provided-- check each path for the requested package");
                // if no version is specified, just get the latest version
                foreach (var pkgPath in dirsToSearch)
                {
                    cmdletPassedIn.WriteDebug(string.Format("Searching through package path: '{0}'", pkgPath));

                    // just search scripts paths
                    if (pkgPath.ToLower().Contains("scripts"))
                    {
                        if (File.Exists(pkgPath))   //check to make sure properly formatted
                        {
                            installedPkgsToReturn.Add(pkgPath);
                        }
                    }
                    else
                    {
                        // modules paths
                        string[] versionsDirs = new string[0];

                        versionsDirs = Directory.GetDirectories(pkgPath);

                        // Check if the pkg path actually has version sub directories.
                        if (versionsDirs.Length != 0)
                        {
                            Array.Sort(versionsDirs, StringComparer.OrdinalIgnoreCase);
                            Array.Reverse(versionsDirs);

                            var pkgXmlFilePath = System.IO.Path.Combine(versionsDirs.First(), "PSGetModuleInfo.xml");

                            // TODO:  check if this xml file exists, if it doesn't check if it exists in a previous version
                            cmdletPassedIn.WriteDebug(string.Format("Found package XML: '{0}'", pkgXmlFilePath));
                            installedPkgsToReturn.Add(pkgXmlFilePath);
                        }
                    }
                }
            }


            // Flatten returned pkgs before displaying output returnedPkgsFound.Flatten().ToList()[0]
            var flattenedPkgs = installedPkgsToReturn.Flatten();



            List <PSObject> foundInstalledPkgs = new List <PSObject>();

            foreach (string xmlFilePath in flattenedPkgs)
            {
                cmdletPassedIn.WriteDebug(string.Format("Reading package metadata from: '{0}'", xmlFilePath));

                // Open xml and read metadata from it
                if (File.Exists(xmlFilePath))
                {
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> nameInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> versionInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> typeInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> descriptionInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> authorInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> companyNameInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> copyrightInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> publishedDateInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> installedDateInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> updatedDateInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> licenseUriInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> projectUriInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> iconUriInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> tagsInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> includesInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> powerShellGetFormatVersionInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> releaseNotesInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> dependenciesInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> repositorySourceLocationInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> repositoryInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> additionalMetadataInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> installedLocationInfo;


                    //var isPrelease = false;
                    using (StreamReader sr = new StreamReader(xmlFilePath))
                    {
                        string text            = sr.ReadToEnd();
                        var    deserializedObj = (PSObject)PSSerializer.Deserialize(text);

                        nameInfo          = deserializedObj.Properties.Match("Name");
                        versionInfo       = deserializedObj.Properties.Match("Version");
                        typeInfo          = deserializedObj.Properties.Match("Type");
                        descriptionInfo   = deserializedObj.Properties.Match("Description");
                        authorInfo        = deserializedObj.Properties.Match("Author");
                        companyNameInfo   = deserializedObj.Properties.Match("CompanyName");
                        copyrightInfo     = deserializedObj.Properties.Match("Copyright");
                        publishedDateInfo = deserializedObj.Properties.Match("PublishedDate");
                        installedDateInfo = deserializedObj.Properties.Match("InstalledDate");
                        updatedDateInfo   = deserializedObj.Properties.Match("UpdatedDate");
                        licenseUriInfo    = deserializedObj.Properties.Match("LicenseUri");
                        projectUriInfo    = deserializedObj.Properties.Match("ProjectUri");
                        iconUriInfo       = deserializedObj.Properties.Match("IconUri");
                        tagsInfo          = deserializedObj.Properties.Match("Tags");
                        includesInfo      = deserializedObj.Properties.Match("Includes");
                        powerShellGetFormatVersionInfo = deserializedObj.Properties.Match("PowerShellGetFormatVersion");
                        releaseNotesInfo             = deserializedObj.Properties.Match("ReleaseNotes");
                        dependenciesInfo             = deserializedObj.Properties.Match("Dependencies");
                        repositorySourceLocationInfo = deserializedObj.Properties.Match("RepositorySourceLocation");
                        repositoryInfo         = deserializedObj.Properties.Match("Repository");
                        additionalMetadataInfo = deserializedObj.Properties.Match("AdditionalMetadata");
                        installedLocationInfo  = deserializedObj.Properties.Match("InstalledLocation");


                        /* // testing adding prerelease parameter
                         * additionalMetadataInfo = deserializedObj.Properties.Match("AdditionalMetadata");
                         * if (additionalMetadataInfo.Any())
                         * {
                         *  isPrelease = additionalMetadataInfo.FirstOrDefault().Value.ToString().Contains("IsPrerelease=true");
                         *  if ((isPrelease == true) && _prerelease) // find a stable version of the pkg {}
                         * }
                         */
                    };

                    // if -Prerelease is not passed in as a parameter, don't allow prerelease pkgs to be returned,
                    // we still want all pkgs to be returned if -Prerelease is passed in as a param
                    //if ((_prerelease == false && isPrelease == false) || _prerelease == true)
                    //{

                    //var foundPkgs = List<PSObject>();

                    PSObject pkgAsPSObject = new PSObject();
                    try
                    {
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Name", nameInfo.Any()? nameInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Version", versionInfo.Any()? versionInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Type", typeInfo.Any()? typeInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Description", descriptionInfo.Any()? descriptionInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Author", authorInfo.Any()? authorInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("CompanyName", companyNameInfo.Any()? companyNameInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Copyright", copyrightInfo.Any()? copyrightInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("PublishedDate", publishedDateInfo.Any()? publishedDateInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("InstalledDate", installedDateInfo.Any()? installedDateInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("UpdatedDate", updatedDateInfo.Any()? updatedDateInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("LicenseUri", licenseUriInfo.Any()? licenseUriInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("ProjectUri", projectUriInfo.Any()? projectUriInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("IconUri", iconUriInfo.Any()? iconUriInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Tags", tagsInfo.Any()? tagsInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Includes", includesInfo.Any()? includesInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("PowerShellGetFormatVersion", powerShellGetFormatVersionInfo.Any()? powerShellGetFormatVersionInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("ReleaseNotes", releaseNotesInfo.Any()? releaseNotesInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Dependencies", dependenciesInfo.Any()? dependenciesInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("RepositorySourceLocation", repositorySourceLocationInfo.Any()? repositorySourceLocationInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Repository", repositoryInfo.Any()? repositoryInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("AdditionalMetadata", additionalMetadataInfo.Any()? additionalMetadataInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("InstalledLocation", installedLocationInfo.Any()? installedLocationInfo.FirstOrDefault().Value : string.Empty));


                        // verify that this works, then add the object to a list and return it
                        //WriteObject(pkgAsPSObject);
                        foundInstalledPkgs.Add(pkgAsPSObject);
                    }
                    catch { }
                }
            }

            // return here
            return(foundInstalledPkgs);
        }
예제 #14
0
        public IToolPackage InstallPackage(PackageId packageId,
                                           VersionRange versionRange         = null,
                                           string targetFramework            = null,
                                           FilePath?nugetConfig              = null,
                                           DirectoryPath?rootConfigDirectory = null,
                                           string[] additionalFeeds          = null,
                                           string verbosity = null)
        {
            var    packageRootDirectory = _store.GetRootPackageDirectory(packageId);
            string rollbackDirectory    = null;

            return(TransactionalAction.Run <IToolPackage>(
                       action: () => {
                var stageDirectory = _store.GetRandomStagingDirectory();
                _fileSystem.Directory.CreateDirectory(stageDirectory.Value);
                rollbackDirectory = stageDirectory.Value;

                var tempProject = new FilePath(Path.Combine(stageDirectory.Value, ProjectFileName));

                // Write a fake project with the requested package id, version, and framework
                _fileSystem.File.WriteAllText(
                    tempProject.Value,
                    $"{packageId};{versionRange?.ToString("S", new VersionRangeFormatter()) ?? "*"};{targetFramework};{stageDirectory.Value}");

                // Perform a restore on the fake project
                _projectRestorer.Restore(
                    tempProject,
                    nugetConfig,
                    verbosity);

                if (_installCallback != null)
                {
                    _installCallback();
                }

                var version = _store.GetStagedPackageVersion(stageDirectory, packageId);
                var packageDirectory = _store.GetPackageDirectory(packageId, version);
                if (_fileSystem.Directory.Exists(packageDirectory.Value))
                {
                    throw new ToolPackageException(
                        string.Format(
                            CommonLocalizableStrings.ToolPackageConflictPackageId,
                            packageId,
                            version.ToNormalizedString()));
                }

                _fileSystem.Directory.CreateDirectory(packageRootDirectory.Value);
                _fileSystem.Directory.Move(stageDirectory.Value, packageDirectory.Value);
                rollbackDirectory = packageDirectory.Value;

                IEnumerable <string> warnings = null;
                _warningsMap.TryGetValue(packageId, out warnings);

                IReadOnlyList <FilePath> packedShims = null;
                _packagedShimsMap.TryGetValue(packageId, out packedShims);

                return new ToolPackageMock(_fileSystem, packageId, version, packageDirectory, warnings: warnings, packagedShims: packedShims);
            },
                       rollback: () => {
                if (rollbackDirectory != null && _fileSystem.Directory.Exists(rollbackDirectory))
                {
                    _fileSystem.Directory.Delete(rollbackDirectory, true);
                }
                if (_fileSystem.Directory.Exists(packageRootDirectory.Value) &&
                    !_fileSystem.Directory.EnumerateFileSystemEntries(packageRootDirectory.Value).Any())
                {
                    _fileSystem.Directory.Delete(packageRootDirectory.Value, false);
                }
            }));
        }
예제 #15
0
 public override string ToString()
 {
     return(Name + " " + (VersionRange?.ToString()));
 }
예제 #16
0
        // This method calls iterates through repositories (by priority order) to search for the pkgs to install
        private List <PSResourceInfo> ProcessRepositories(
            string[] repository,
            bool trustRepository,
            PSCredential credential,
            bool skipDependencyCheck)
        {
            var listOfRepositories = RepositorySettings.Read(repository, out string[] _);
            var yesToAll           = false;
            var noToAll            = false;

            var findHelper = new FindHelper(_cancellationToken, _cmdletPassedIn);
            List <PSResourceInfo> allPkgsInstalled = new List <PSResourceInfo>();

            foreach (var repo in listOfRepositories)
            {
                // If no more packages to install, then return
                if (!_pkgNamesToInstall.Any())
                {
                    return(allPkgsInstalled);
                }

                string repoName = repo.Name;
                _cmdletPassedIn.WriteVerbose(string.Format("Attempting to search for packages in '{0}'", repoName));

                // Source is only trusted if it's set at the repository level to be trusted, -TrustRepository flag is true, -Force flag is true
                // OR the user issues trust interactively via console.
                var sourceTrusted = true;
                if (repo.Trusted == false && !trustRepository && !_force)
                {
                    _cmdletPassedIn.WriteVerbose("Checking if untrusted repository should be used");

                    if (!(yesToAll || noToAll))
                    {
                        // Prompt for installation of package from untrusted repository
                        var message = string.Format(CultureInfo.InvariantCulture, MsgInstallUntrustedPackage, repoName);
                        sourceTrusted = _cmdletPassedIn.ShouldContinue(message, MsgRepositoryNotTrusted, true, ref yesToAll, ref noToAll);
                    }
                }

                if (!sourceTrusted && !yesToAll)
                {
                    continue;
                }

                _cmdletPassedIn.WriteVerbose("Untrusted repository accepted as trusted source.");

                // If it can't find the pkg in one repository, it'll look for it in the next repo in the list
                var isLocalRepo = repo.Url.AbsoluteUri.StartsWith(Uri.UriSchemeFile + Uri.SchemeDelimiter, StringComparison.OrdinalIgnoreCase);

                // Finds parent packages and dependencies
                IEnumerable <PSResourceInfo> pkgsFromRepoToInstall = findHelper.FindByResourceName(
                    name: _pkgNamesToInstall.ToArray(),
                    type: ResourceType.None,
                    version: _versionRange != null ? _versionRange.OriginalString : null,
                    prerelease: _prerelease,
                    tag: null,
                    repository: new string[] { repoName },
                    credential: credential,
                    includeDependencies: !skipDependencyCheck);

                if (!pkgsFromRepoToInstall.Any())
                {
                    _cmdletPassedIn.WriteVerbose(string.Format("None of the specified resources were found in the '{0}' repository.", repoName));
                    // Check in the next repository
                    continue;
                }

                // Select the first package from each name group, which is guaranteed to be the latest version.
                // We should only have one version returned for each package name
                // e.g.:
                // PackageA (version 1.0)
                // PackageB (version 2.0)
                // PackageC (version 1.0)
                pkgsFromRepoToInstall = pkgsFromRepoToInstall.GroupBy(
                    m => new { m.Name }).Select(
                    group => group.First()).ToList();

                // Check to see if the pkgs (including dependencies) are already installed (ie the pkg is installed and the version satisfies the version range provided via param)
                if (!_reinstall)
                {
                    pkgsFromRepoToInstall = FilterByInstalledPkgs(pkgsFromRepoToInstall);
                }

                if (!pkgsFromRepoToInstall.Any())
                {
                    continue;
                }

                List <PSResourceInfo> pkgsInstalled = InstallPackage(
                    pkgsFromRepoToInstall,
                    repo.Url.AbsoluteUri,
                    credential,
                    isLocalRepo);

                foreach (PSResourceInfo pkg in pkgsInstalled)
                {
                    _pkgNamesToInstall.RemoveAll(x => x.Equals(pkg.Name, StringComparison.InvariantCultureIgnoreCase));
                }

                allPkgsInstalled.AddRange(pkgsInstalled);
            }

            // At this only package names left were those which could not be found in registered repositories
            foreach (string pkgName in _pkgNamesToInstall)
            {
                var message = String.Format("Package '{0}' with requested version range {1} could not be installed as it was not found in any registered repositories",
                                            pkgName,
                                            _versionRange.ToString());
                var ex = new ArgumentException(message);
                var ResourceNotFoundError = new ErrorRecord(ex, "ResourceNotFoundError", ErrorCategory.ObjectNotFound, null);
                _cmdletPassedIn.WriteError(ResourceNotFoundError);
            }

            return(allPkgsInstalled);
        }
예제 #17
0
        private async Task <PackageIdentity> GetLatestPackageInternalAsync(string packageId, VersionRange versionRange, CancellationToken cancellationToken)
        {
            versionRange = new VersionRange(versionRange ?? VersionRange.All, new FloatRange(VersionFloatBehavior));

            var packageVersions = await this.GetPackageVersionsAsync(packageId, cancellationToken).ConfigureAwait(false);

            if (!packageVersions.Any())
            {
                throw new PackageNotFoundException($"Package \"{packageId}\" not found in repository {this.feedUrl.ToString()}");
            }

            var packageVersion = versionRange.FindBestMatch(packageVersions) ??
                                 throw new PackageVersionNotFoundException($"Package \"{packageId}\" has no versions compatible with range \"{versionRange.ToString()}\".");

            return(new PackageIdentity(packageId, packageVersion));
        }