Example #1
0
        private IEnumerable <string> GetPackageAssemblyNames(string path)
        {
            var compatibilityProvider = new DefaultCompatibilityProvider();
            var folderReader          = new PackageFolderReader(Path.Combine(path, _fileSystem.PackagesFolder));
            var nupkgFiles            = folderReader.GetFiles().Where(x => Path.GetExtension(x).ToLowerInvariant() == ".nupkg");

            var packagesConfig = XDocument.Parse(File.ReadAllText(Path.Combine(path, _fileSystem.PackagesFile)));

            var reader   = new PackagesConfigReader(packagesConfig);
            var contents = reader.GetPackages();

            var result = new List <string>();

            foreach (var nupkg in nupkgFiles)
            {
                var stream        = folderReader.GetStream(nupkg);
                var packageReader = new PackageReader(stream);

                var identity = packageReader.GetIdentity();
                var packagesConfigReference = contents.FirstOrDefault(x => x.PackageIdentity.Id == identity.Id && x.PackageIdentity.Version == identity.Version);

                if (packagesConfigReference == null)
                {
                    break;
                }

                var packageContents = packageReader.GetLibItems().Where(x => compatibilityProvider.IsCompatible(x.TargetFramework, packagesConfigReference.TargetFramework)).
                                      SelectMany(x => x.Items.Where(i => Path.GetExtension(i).ToLowerInvariant() == ".dll"));

                result.AddRange(packageContents);
            }

            return(result);
        }
Example #2
0
        private IEnumerable <PackageReference> LoadPackages(string projectDir)
        {
            IEnumerable <PackageReference> packageReferences = new List <PackageReference>();

            string packagesFile = Path.Combine(projectDir, "packages.config");

            if (File.Exists(packagesFile))
            {
                try
                {
                    XDocument xDocument = NuGet.Common.XmlUtility.Load(packagesFile);
                    var       reader    = new PackagesConfigReader(xDocument);
                    packageReferences = reader.GetPackages();
                }
                catch (XmlException ex)
                {
                    Logger.LogError(ex, "Error while parsing xml for file {0}", packagesFile);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Error while parsing file {0}", packagesFile);
                }
            }
            return(packageReferences);
        }
Example #3
0
        protected IEnumerable <Packaging.PackageReference> GetInstalledPackageReferences(
            string projectConfigFilePath,
            bool allowDuplicatePackageIds)
        {
            if (File.Exists(projectConfigFilePath))
            {
                try
                {
                    var xDocument = XDocument.Load(projectConfigFilePath);
                    var reader    = new PackagesConfigReader(XDocument.Load(projectConfigFilePath));
                    return(reader.GetPackages(allowDuplicatePackageIds));
                }
                catch (XmlException ex)
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("Error_PackagesConfigParseError"),
                        projectConfigFilePath,
                        ex.Message);

                    throw new CommandLineException(message);
                }
            }

            return(Enumerable.Empty <Packaging.PackageReference>());
        }
        public void PackagesConfigWriter_Basic()
        {
            var stream = new MemoryStream();

            using (PackagesConfigWriter writer = new PackagesConfigWriter(stream))
            {
                writer.WriteMinClientVersion(NuGetVersion.Parse("3.0.1"));

                writer.WritePackageEntry("packageB", NuGetVersion.Parse("2.0.0"), NuGetFramework.Parse("portable-net45+win8"));

                writer.WritePackageEntry("packageA", NuGetVersion.Parse("1.0.1"), NuGetFramework.Parse("net45"));
            }

            stream.Seek(0, SeekOrigin.Begin);

            var xml = XDocument.Load(stream);

            Assert.Equal("utf-8", xml.Declaration.Encoding);

            PackagesConfigReader reader = new PackagesConfigReader(xml);

            Assert.Equal("3.0.1", reader.GetMinClientVersion().ToNormalizedString());

            var packages = reader.GetPackages().ToArray();
            Assert.Equal("packageA", packages[0].PackageIdentity.Id);
            Assert.Equal("packageB", packages[1].PackageIdentity.Id);

            Assert.Equal("1.0.1", packages[0].PackageIdentity.Version.ToNormalizedString());
            Assert.Equal("2.0.0", packages[1].PackageIdentity.Version.ToNormalizedString());

            Assert.Equal("net45", packages[0].TargetFramework.GetShortFolderName());
            Assert.Equal("portable-net45+win8", packages[1].TargetFramework.GetShortFolderName());
        }
        public void PackagesConfigWriter_Basic()
        {
            MemoryStream stream = new MemoryStream();

            using (PackagesConfigWriter writer = new PackagesConfigWriter(stream))
            {
                writer.WriteMinClientVersion(NuGetVersion.Parse("3.0.1"));

                writer.WritePackageEntry("packageB", NuGetVersion.Parse("2.0.0"), NuGetFramework.Parse("portable-net45+win8"));

                writer.WritePackageEntry("packageA", NuGetVersion.Parse("1.0.1"), NuGetFramework.Parse("net45"));
            }

            stream.Seek(0, SeekOrigin.Begin);

            var xml = XDocument.Load(stream);

            Assert.Equal("utf-8", xml.Declaration.Encoding);

            PackagesConfigReader reader = new PackagesConfigReader(xml);

            Assert.Equal("3.0.1", reader.GetMinClientVersion().ToNormalizedString());

            var packages = reader.GetPackages().ToArray();

            Assert.Equal("packageA", packages[0].PackageIdentity.Id);
            Assert.Equal("packageB", packages[1].PackageIdentity.Id);

            Assert.Equal("1.0.1", packages[0].PackageIdentity.Version.ToNormalizedString());
            Assert.Equal("2.0.0", packages[1].PackageIdentity.Version.ToNormalizedString());

            Assert.Equal("net45", packages[0].TargetFramework.GetShortFolderName());
            Assert.Equal("portable-net45+win8", packages[1].TargetFramework.GetShortFolderName());
        }
        private List <PackageReference> GetInstalledPackagesList()
        {
            try
            {
                var xml = GetPackagesConfig();

                if (xml != null)
                {
                    var reader = new PackagesConfigReader(xml);
                    return(reader.GetPackages().ToList());
                }
            }
            catch (Exception ex)
                when(ex is XmlException ||
                     ex is PackagesConfigReaderException)
                {
                    throw new InvalidOperationException(string.Format(
                                                            CultureInfo.CurrentCulture,
                                                            Strings.ErrorLoadingPackagesConfig,
                                                            FullPath,
                                                            ex.Message));
                }

            return(new List <PackageReference>());
        }
        public void PackagesConfigWriter_Remove()
        {
            // Arrange
            using (var stream = new MemoryStream())
            {
                // Act
                using (var writer = new PackagesConfigWriter(stream, true))
                {
                    writer.AddPackageEntry("packageB", NuGetVersion.Parse("2.0.0"), NuGetFramework.Parse("portable-net45+win8"));

                    writer.AddPackageEntry("packageA", NuGetVersion.Parse("1.0.1"), NuGetFramework.Parse("net45"));

                    writer.RemovePackageEntry("packageB", NuGetVersion.Parse("2.0.0"), NuGetFramework.Parse("portable-net45+win8"));
                }

                stream.Seek(0, SeekOrigin.Begin);

                var xml = XDocument.Load(stream);

                // Assert
                Assert.Equal("utf-8", xml.Declaration.Encoding);

                var reader = new PackagesConfigReader(xml);

                var packages = reader.GetPackages().ToArray();
                Assert.Equal("1", packages.Count().ToString());
                Assert.Equal("packageA", packages[0].PackageIdentity.Id);
                Assert.Equal("1.0.1", packages[0].PackageIdentity.Version.ToNormalizedString());
                Assert.Equal("net45", packages[0].TargetFramework.GetShortFolderName());
            }
        }
Example #8
0
        private void LoadFromPackagesConfig()
        {
            IEnumerable <PackageReference> packageReferences = new List <PackageReference>();

            string packageConfig = Path.Combine(_projectDir, Constants.PackagesConfig);

            if (File.Exists(packageConfig))
            {
                try
                {
                    using var fileStream = new FileStream(packageConfig, FileMode.Open);
                    var configReader = new PackagesConfigReader(fileStream);
                    var packages     = configReader.GetPackages(true);

                    packages?.ToList().ForEach(package => {
                        var reference = new ExternalReference()
                        {
                            Identity = package.PackageIdentity.Id, Version = package.PackageIdentity.Version.OriginalVersion
                        };
                        if (!_externalReferences.NugetReferences.Contains(reference))
                        {
                            _externalReferences.NugetReferences.Add(reference);
                        }
                    });
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Error while parsing file {0}", packageConfig);
                }
            }
        }
        private HashSet <PackageReference> GetInstalledPackageReferences(string projectConfigFilePath)
        {
            if (File.Exists(projectConfigFilePath))
            {
                var reader = new PackagesConfigReader(XDocument.Load(projectConfigFilePath));
                return(new HashSet <PackageReference>(reader.GetPackages(), new PackageReferenceComparer()));
            }

            return(new HashSet <PackageReference>(new PackageReferenceComparer()));
        }
Example #10
0
 private static IEnumerable <PackageReference> GetInstalledPackageReferencesFromConfigFile(
     string projectConfigFilePath,
     bool allowDuplicatePackageIds)
 {
     using (var file = File.Open(projectConfigFilePath, FileMode.Open, FileAccess.Read))
     {
         var reader = new PackagesConfigReader(file);
         return(reader.GetPackages(allowDuplicatePackageIds));
     }
 }
        private List <PackageReference> GetInstalledPackagesList()
        {
            if (File.Exists(FullPath))
            {
                var reader = new PackagesConfigReader(XDocument.Load(FullPath));
                return(reader.GetPackages().ToList());
            }

            return(new List <PackageReference>());
        }
        public static PackagesLockFile FromPackagesConfigFile(
            string pcFile,
            NuGetFramework projectTfm,
            string packagesFolderPath,
            CancellationToken token)
        {
            if (pcFile == null)
            {
                throw new ArgumentNullException(nameof(pcFile));
            }
            if (!File.Exists(pcFile))
            {
                throw new FileNotFoundException(string.Format(Strings.Error_FileDoesNotExist, pcFile), pcFile);
            }
            if (projectTfm == null)
            {
                throw new ArgumentNullException(nameof(projectTfm));
            }
            if (packagesFolderPath == null)
            {
                throw new ArgumentNullException(nameof(packagesFolderPath));
            }
            if (!Directory.Exists(packagesFolderPath))
            {
                throw new DirectoryNotFoundException(string.Format(Strings.Error_DirectoryDoesNotExist, packagesFolderPath));
            }

            var lockFile = new PackagesLockFile();
            var target   = new PackagesLockFileTarget();

            lockFile.Targets.Add(target);
            target.TargetFramework = projectTfm;

            using (var stream = File.OpenRead(pcFile))
            {
                var contentHashUtil = new PackagesConfigContentHashProvider(new FolderNuGetProject(packagesFolderPath));

                var reader = new PackagesConfigReader(stream);
                foreach (var package in reader.GetPackages(allowDuplicatePackageIds: true))
                {
                    var dependency = new LockFileDependency
                    {
                        Id               = package.PackageIdentity.Id,
                        ContentHash      = contentHashUtil.GetContentHash(package.PackageIdentity, token),
                        RequestedVersion = new VersionRange(package.PackageIdentity.Version, includeMinVersion: true, package.PackageIdentity.Version, includeMaxVersion: true),
                        ResolvedVersion  = package.PackageIdentity.Version,
                        Type             = PackageDependencyType.Direct
                    };

                    target.Dependencies.Add(dependency);
                }
            }

            return(lockFile);
        }
        public void PackagesConfigWriter_BasicWithDifferentCulture()
        {
            var currentCulture   = CultureInfo.CurrentCulture;
            var currentUICulture = CultureInfo.CurrentUICulture;

            try
            {
                var calendar = new CultureInfo("he-IL");
                calendar.DateTimeFormat.Calendar = new HebrewCalendar();

                CultureInfo.CurrentCulture   = calendar;
                CultureInfo.CurrentUICulture = calendar;

                // Arrange
                using (var testFolder = TestDirectory.Create())
                {
                    var path = Path.Combine(testFolder + "packages.config");

                    // Act
                    using (var writer = new PackagesConfigWriter(path, true))
                    {
                        writer.WriteMinClientVersion(NuGetVersion.Parse("3.0.1"));

                        writer.AddPackageEntry("packageB", NuGetVersion.Parse("2.0.0"), NuGetFramework.Parse("portable-net45+win8"));

                        writer.AddPackageEntry("packageA", NuGetVersion.Parse("1.0.1"), NuGetFramework.Parse("net45"));
                    }

                    // Assert
                    var xml = XDocument.Load(path);

                    // Assert
                    Assert.Equal("utf-8", xml.Declaration.Encoding);

                    var reader = new PackagesConfigReader(xml);

                    Assert.Equal("3.0.1", reader.GetMinClientVersion().ToNormalizedString());

                    var packages = reader.GetPackages().ToArray();
                    Assert.Equal("packageA", packages[0].PackageIdentity.Id);
                    Assert.Equal("packageB", packages[1].PackageIdentity.Id);

                    Assert.Equal("1.0.1", packages[0].PackageIdentity.Version.ToNormalizedString());
                    Assert.Equal("2.0.0", packages[1].PackageIdentity.Version.ToNormalizedString());

                    Assert.Equal("net45", packages[0].TargetFramework.GetShortFolderName());
                    Assert.Equal("portable-net45+win8", packages[1].TargetFramework.GetShortFolderName());
                }
            }
            finally
            {
                CultureInfo.CurrentCulture   = currentCulture;
                CultureInfo.CurrentUICulture = currentUICulture;
            }
        }
Example #14
0
        public IEnumerable <IPackageReference> FindReferences(string path)
        {
            if (!File.Exists(path))
            {
                yield break;
            }

            var packagesConfig = XDocument.Parse(File.ReadAllText(path));
            var reader         = new PackagesConfigReader(packagesConfig);

            var references = reader.GetPackages().ToList();

            if (references.Any())
            {
                foreach (var packageReference in references)
                {
                    yield return(new ScriptCs.Dnx.Core.PackageReference(
                                     packageReference.PackageIdentity.Id,
                                     new FrameworkName(packageReference.TargetFramework.DotNetFrameworkName),
                                     packageReference.PackageIdentity.Version.ToString()));
                }

                yield break;
            }

            //todo:
            // No packages.config, check packages folder
            //var packagesFolder = Path.Combine(_fileSystem.GetWorkingDirectory(path), _fileSystem.PackagesFolder);
            //if (!_fileSystem.DirectoryExists(packagesFolder))
            //{
            //    yield break;
            //}

            //var repository = new LocalPackageRepository(packagesFolder);

            //var arbitraryPackages = repository.GetPackages();
            //if (!arbitraryPackages.Any())
            //{
            //    yield break;
            //}

            //foreach (var arbitraryPackage in arbitraryPackages)
            //{
            //    var newestFramework = GetNewestSupportedFramework(arbitraryPackage)
            //                          ?? VersionUtility.EmptyFramework;

            //    yield return new PackageReference(
            //        arbitraryPackage.Id,
            //        newestFramework,
            //        arbitraryPackage.Version.Version,
            //        arbitraryPackage.Version.SpecialVersion);
            //}
        }
Example #15
0
        public void PackagesConfigReader_InvalidAllowedVersions()
        {
            var doc = XDocument.Parse(
                @"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id=""test"" version=""1.0"" allowedVersions=""xyz""/>
</packages>");
            var reader = new PackagesConfigReader(doc);

            var ex = Assert.Throws <PackagesConfigReaderException>(() => reader.GetPackages());

            Assert.Equal(ex.Message, "Invalid allowedVersions for package id 'test': 'xyz'");
        }
 private List <PackageReference> GetPackageReferencesFromConfigFile()
 {
     try
     {
         XDocument xDocument = XmlUtility.Load(_packageConfigFile);
         var       reader    = new PackagesConfigReader(xDocument);
         return(reader.GetPackages(true).ToList());
     }
     catch (XmlException ex)
     {
         throw new PortingAssistantClientException("Unable to parse packages.config file", ex);
     }
 }
Example #17
0
        public void PackagesConfigReader_BadId()
        {
            var doc = XDocument.Parse(
                @"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id="""" />
</packages>");
            var reader = new PackagesConfigReader(doc);

            var ex = Assert.Throws <PackagesConfigReaderException>(() => reader.GetPackages());

            Assert.Equal(ex.Message, "Null or empty package id");
        }
Example #18
0
        public void PackagesConfigReader_Basic3()
        {
            var reader = new PackagesConfigReader(PackagesConf3);

            var version = reader.GetMinClientVersion();

            Assert.Equal("3.0.0", version.ToNormalizedString());

            var packageEntries = reader.GetPackages().ToArray();

            Assert.Equal(2, packageEntries.Length);
            Assert.Equal("Newtonsoft.Json", packageEntries[0].PackageIdentity.Id);
            Assert.Equal("TestPackage", packageEntries[1].PackageIdentity.Id);
        }
Example #19
0
        private IEnumerable <PackageIdentity> CreatePackageIdentitiesFromPackagesConfig()
        {
            var identities = Enumerable.Empty <PackageIdentity>();

            try
            {
                // Example: install-package https://raw.githubusercontent.com/NuGet/json-ld.net/master/src/JsonLD/packages.config
                if (UriHelper.IsHttpSource(Id))
                {
                    var request  = (HttpWebRequest)WebRequest.Create(Id);
                    var response = (HttpWebResponse)request.GetResponse();
                    // Read data via the response stream
                    var resStream = response.GetResponseStream();

                    var reader      = new PackagesConfigReader(resStream);
                    var packageRefs = reader.GetPackages();
                    identities = packageRefs.Select(v => v.PackageIdentity);
                }
                else
                {
                    // Example: install-package c:\temp\packages.config
                    using (var stream = new FileStream(Id, FileMode.Open))
                    {
                        var reader      = new PackagesConfigReader(stream);
                        var packageRefs = reader.GetPackages();
                        identities = packageRefs.Select(v => v.PackageIdentity);
                    }
                }

                // Set _allowPrerelease to true if any of the identities is prerelease version.
                if (identities != null &&
                    identities.Any())
                {
                    foreach (var identity in identities)
                    {
                        if (identity.Version.IsPrerelease)
                        {
                            _allowPrerelease = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogCore(MessageLevel.Error, string.Format(CultureInfo.CurrentCulture, Resources.Cmdlet_FailToParsePackages, Id, ex.Message));
            }

            return(identities);
        }
        public void PackagesConfigReader_Basic3()
        {
            var reader = new PackagesConfigReader(PackagesConf3);

            var version = reader.GetMinClientVersion();

            Assert.Equal("3.0.0", version.ToNormalizedString());

            var packageEntries = reader.GetPackages().ToArray();

            Assert.Equal(2, packageEntries.Length);
            Assert.Equal("Newtonsoft.Json", packageEntries[0].PackageIdentity.Id);
            Assert.Equal("TestPackage", packageEntries[1].PackageIdentity.Id);
        }
Example #21
0
        public bool IsInstalled(IPackageIdentity package)
        {
            Ensure.NotNull(package, "package");

            if (!File.Exists(ConfigFilePath))
            {
                return(false);
            }

            using (Stream fileContent = new FileStream(ConfigFilePath, FileMode.Open))
            {
                PackagesConfigReader reader = new PackagesConfigReader(fileContent);
                return(reader.GetPackages().Any(p => p.PackageIdentity.Id == package.Id && p.PackageIdentity.Version.ToFullString() == package.Version));
            }
        }
Example #22
0
        public bool IsInstalled(IPackageIdentity package)
        {
            Ensure.NotNull(package, "package");

            if (!File.Exists(ConfigFilePath))
            {
                return(false);
            }

            using (Stream fileContent = new FileStream(ConfigFilePath, FileMode.Open))
            {
                PackagesConfigReader reader = new PackagesConfigReader(fileContent);
                return(reader.GetPackages().Any(p => string.Equals(p.PackageIdentity.Id, package.Id, StringComparison.CurrentCultureIgnoreCase) && string.Equals(p.PackageIdentity.Version.ToFullString(), package.Version, StringComparison.CurrentCultureIgnoreCase)));
            }
        }
        public void PackagesConfigWriter_UpdateAttributesFromOriginalConfig()
        {
            // Arrange
            using (var stream = new MemoryStream())
                using (var stream2 = new MemoryStream())
                {
                    // Act
                    using (var writer = new PackagesConfigWriter(stream, true))
                    {
                        var vensionRange      = new VersionRange(NuGetVersion.Parse("0.5.0"));
                        var packageIdentityA  = new PackageIdentity("packageA", NuGetVersion.Parse("1.0.1"));
                        var packageReferenceA = new PackageReference(packageIdentityA, NuGetFramework.Parse("net45"),
                                                                     userInstalled: false, developmentDependency: false, requireReinstallation: true, allowedVersions: vensionRange);

                        writer.AddPackageEntry(packageReferenceA);
                    }

                    stream.Seek(0, SeekOrigin.Begin);
                    var xml = XDocument.Load(stream);

                    var packageIdentityB  = new PackageIdentity("packageA", NuGetVersion.Parse("3.0.1"));
                    var packageReferenceB = new PackageReference(packageIdentityB, NuGetFramework.Parse("dnxcore50"),
                                                                 userInstalled: false, developmentDependency: false, requireReinstallation: false);

                    using (var writer = new PackagesConfigWriter(stream2, true))
                    {
                        writer.UpdateOrAddPackageEntry(xml, packageReferenceB);
                    }

                    stream2.Seek(0, SeekOrigin.Begin);
                    var xml2   = XDocument.Load(stream2);
                    var reader = new PackagesConfigReader(xml2);

                    // Assert

                    var packages = reader.GetPackages().ToArray();
                    Assert.Equal("1", packages.Count().ToString());
                    Assert.Equal("packageA", packages[0].PackageIdentity.Id);
                    Assert.Equal("3.0.1", packages[0].PackageIdentity.Version.ToNormalizedString());
                    Assert.Equal("dnxcore50", packages[0].TargetFramework.GetShortFolderName());

                    // Verify allowedVersions attribute is kept after package update.
                    Assert.Equal("[0.5.0, )", packages[0].AllowedVersions.ToNormalizedString());

                    // Verify that RequireReinstallation attribute is removed after package upate.
                    Assert.Equal("False", packages[0].RequireReinstallation.ToString());
                }
        }
Example #24
0
        /// <summary>
        /// Return list of package identities parsed from packages.config
        /// </summary>
        IEnumerable <PackageIdentity> CreatePackageIdentitiesFromPackagesConfig()
        {
            IEnumerable <PackageIdentity> identities = Enumerable.Empty <PackageIdentity> ();

            try {
                // Example: install-package https://raw.githubusercontent.com/NuGet/json-ld.net/master/src/JsonLD/packages.config
                if (UriHelper.IsHttpSource(Id))
                {
                    HttpWebRequest  request  = (HttpWebRequest)WebRequest.Create(Id);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    // Read data via the response stream
                    Stream resStream = response.GetResponseStream();

                    var reader      = new PackagesConfigReader(resStream);
                    var packageRefs = reader.GetPackages();
                    identities = packageRefs.Select(v => v.PackageIdentity);
                }
                else
                {
                    // Example: install-package c:\temp\packages.config
                    using (FileStream stream = new FileStream(Id, FileMode.Open)) {
                        var reader      = new PackagesConfigReader(stream);
                        var packageRefs = reader.GetPackages();
                        identities = packageRefs.Select(v => v.PackageIdentity);
                    }
                }

                // Set _allowPrerelease to true if any of the identities is prerelease version.
                if (identities != null &&
                    identities.Any())
                {
                    foreach (PackageIdentity identity in identities)
                    {
                        if (identity.Version.IsPrerelease)
                        {
                            allowPrerelease = true;
                            break;
                        }
                    }
                }
            } catch (Exception ex) {
                Log(MessageLevel.Error, GettextCatalog.GetString("Failed to parse package identities from file {0} with exception: {1}", Id, ex.Message));
            }

            return(identities);
        }
Example #25
0
        public void PackagesConfigReader_DuplicateEntries()
        {
            var doc = XDocument.Parse(
                @"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id=""test1"" version=""1.0""/>
  <package id=""test1"" version=""1.0""/>

  <package id=""test2"" version=""1.0""/>
  <package id=""test2"" version=""1.0""/>
</packages>");
            var reader = new PackagesConfigReader(doc);

            var ex = Assert.Throws <PackagesConfigReaderException>(() => reader.GetPackages());

            Assert.Equal(ex.Message, "There are duplicate packages: test1, test2");
        }
Example #26
0
        public void PackagesConfigReader_DuplicateEntriesWithNonNormalizedVersions()
        {
            // Arrange
            var doc = XDocument.Parse(
                @"<?xml version=""1.0"" encoding=""utf-8""?>
                <packages>
                  <package id=""test1"" version=""1.1.0""/>
                  <package id=""test1"" version=""1.1""/>
                </packages>");
            var reader = new PackagesConfigReader(doc);

            // Act
            var ex = Assert.Throws <PackagesConfigReaderException>(() =>
                                                                   reader.GetPackages(allowDuplicatePackageIds: true));

            // Assert
            Assert.Equal(ex.Message, "There are duplicate packages: test1.1.1.0");
        }
Example #27
0
        public void PackagesConfigReader_AllowDuplicateEntriesNoFailures()
        {
            // Arrange
            var doc = XDocument.Parse(
                @"<?xml version=""1.0"" encoding=""utf-8""?>
                <packages>
                  <package id=""test1"" version=""1.0""/>
                  <package id=""test1"" version=""1.1.0""/>
                  <package id=""test2"" version=""1.0""/>
                  <package id=""test2"" version=""2.0""/>
                </packages>");
            var reader = new PackagesConfigReader(doc);

            // Act
            var packages = reader.GetPackages(allowDuplicatePackageIds: true);

            // Assert
            Assert.Equal(4, packages.Count());
        }
Example #28
0
        public static NuGet.Packaging.PackageReference GetPackageReference(this ICakeContext context, DirectoryPath path, string packageId)
        {
            if (!path.IsRelative)
            {
                throw new CakeException("DirectoryPath must be relative!");
            }

            var packagePath = path.CombineWithFilePath(new FilePath("packages.config"));

            if (!System.IO.File.Exists(packagePath.FullPath))
            {
                throw new CakeException(string.Format("Could not find a packages.config file in '{0}'", path.FullPath));
            }

            var document = XDocument.Load(packagePath.FullPath);
            var reader   = new PackagesConfigReader(document);

            return(reader.GetPackages().FirstOrDefault(x => x.PackageIdentity.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase)));
        }
Example #29
0
        public IOperationResponse Detect(Project project, string nugetPackageName)
        {
            var packagesConfigPath = Path.Combine(project.Directory, "packages.config");

            if (!File.Exists(Path.Combine(packagesConfigPath)))
            {
                return(OperationResponse.Error(Resources.Info.Errors.SeedBucketProjectCouldNotBeFound));
            }

            var document = XDocument.Load(packagesConfigPath);
            var reader   = new PackagesConfigReader(document);

            return(reader
                   .GetPackages()
                   .Select(p => p.PackageIdentity.Id)
                   .Any(txt => txt.Equals(nugetPackageName, StringComparison.OrdinalIgnoreCase))
                ? OperationResponse.Success()
                : OperationResponse.Error(Resources.Info.Errors.SeedBucketProjectCouldNotBeFound));
        }
        public void ConvertProject(string projectPath)
        {
            string packagesConfigPath = Path.Combine(Path.GetDirectoryName(projectPath), "packages.config");

            if (!File.Exists(packagesConfigPath))
            {
                return;
            }

            ProjectRootElement packagesProps = GetPackagesPropsOrNull();

            PackagesConfigReader packagesConfigReader = new PackagesConfigReader(XDocument.Load(packagesConfigPath));

            List <PackageIdentity> packages = packagesConfigReader.GetPackages(allowDuplicatePackageIds: true).Select(i => i.PackageIdentity).ToList();

            ProjectRootElement project = ProjectRootElement.Open(projectPath, _projectCollection, preserveFormatting: true);

            try
            {
                RemoveImports(project, packages);

                RemoveTargets(project);

                RemoveProperties(project);

                RemoveItems(project);

                ReplaceReferences(project, packages, packagesProps);

                project.Save();

                if (packagesProps != null)
                {
                    packagesProps.Save();
                }

                File.Delete(packagesConfigPath);
            }
            catch (Exception e)
            {
                Console.WriteLine($"Failed to convert '{projectPath}' : {e}");
            }
        }
Example #31
0
        public static IEnumerable <NuGet.Packaging.PackageReference> GetPackageReferences(this ICakeContext context, DirectoryPath path)
        {
            if (!path.IsRelative)
            {
                throw new CakeException("DirectoryPath must be relative!");
            }

            var packagePath = path.CombineWithFilePath(new FilePath("packages.config"));

            if (!System.IO.File.Exists(packagePath.FullPath))
            {
                throw new CakeException(string.Format("Could not find a packages.config file in '{0}'", path.FullPath));
            }

            var document = XDocument.Load(packagePath.FullPath);
            var reader   = new PackagesConfigReader(document);

            return(reader.GetPackages());
        }
Example #32
0
        public void PackagesConfigReader_Basic2()
        {
            var reader = new PackagesConfigReader(PackagesConf2);

            var version = reader.GetMinClientVersion();

            Assert.Equal("2.5.0", version.ToNormalizedString());

            var packageEntries = reader.GetPackages().ToArray();

            Assert.Equal(1, packageEntries.Length);
            Assert.Equal("Newtonsoft.Json", packageEntries[0].PackageIdentity.Id);
            Assert.Equal("6.0.4", packageEntries[0].PackageIdentity.Version.ToNormalizedString());
            Assert.Equal("net45", packageEntries[0].TargetFramework.GetShortFolderName());
            Assert.True(packageEntries[0].HasAllowedVersions);
            Assert.True(packageEntries[0].IsDevelopmentDependency);
            Assert.True(packageEntries[0].IsUserInstalled);
            Assert.True(packageEntries[0].RequireReinstallation);
            Assert.Equal("[6.0.0, )", packageEntries[0].AllowedVersions.ToString());
        }
        public void PackagesConfigReader_Basic2()
        {
            var reader = new PackagesConfigReader(PackagesConf2);

            var version = reader.GetMinClientVersion();

            Assert.Equal("2.5.0", version.ToNormalizedString());

            var packageEntries = reader.GetPackages().ToArray();

            Assert.Equal(1, packageEntries.Length);
            Assert.Equal("Newtonsoft.Json", packageEntries[0].PackageIdentity.Id);
            Assert.Equal("6.0.4", packageEntries[0].PackageIdentity.Version.ToNormalizedString());
            Assert.Equal("net45", packageEntries[0].TargetFramework.GetShortFolderName());
            Assert.True(packageEntries[0].HasAllowedVersions);
            Assert.True(packageEntries[0].IsDevelopmentDependency);
            Assert.True(packageEntries[0].IsUserInstalled);
            Assert.True(packageEntries[0].RequireReinstallation);
            Assert.Equal("[6.0.0, )", packageEntries[0].AllowedVersions.ToString());
        }
        public void PackagesConfigReader_InvalidAllowedVersions()
        {
            var doc = XDocument.Parse(
@"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id=""test"" version=""1.0"" allowedVersions=""xyz""/>
</packages>");
            var reader = new PackagesConfigReader(doc);

            var ex = Assert.Throws<PackagesConfigReaderException>(() => reader.GetPackages());
            Assert.Equal(ex.Message, "Invalid allowedVersions for package id 'test': 'xyz'");
        }
        public void PackagesConfigReader_BadId()
        {
            var doc = XDocument.Parse(
@"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id="""" />
</packages>");
            var reader = new PackagesConfigReader(doc);

            var ex = Assert.Throws<PackagesConfigReaderException>(() => reader.GetPackages());
            Assert.Equal(ex.Message, "Null or empty package id");
        }
        public void PackagesConfigReader_DuplicateEntries()
        {
            var doc = XDocument.Parse(
@"<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
  <package id=""test1"" version=""1.0""/>
  <package id=""test1"" version=""1.0""/>

  <package id=""test2"" version=""1.0""/>
  <package id=""test2"" version=""1.0""/>
</packages>");
            var reader = new PackagesConfigReader(doc);

            var ex = Assert.Throws<PackagesConfigReaderException>(() => reader.GetPackages());
            Assert.Equal(ex.Message, "There are duplicate packages: test1, test2");
        }