Ejemplo n.º 1
0
        private static bool IsPackageSemVer2(NuspecReader package)
        {
            if (package.GetVersion().IsSemVer2())
            {
                return(true);
            }

            if (package.GetDependencyGroups() != null)
            {
                foreach (var dependencySet in package.GetDependencyGroups())
                {
                    foreach (var dependency in dependencySet.Packages)
                    {
                        var range = dependency.VersionRange;
                        if (range == null)
                        {
                            continue;
                        }

                        if (range.MinVersion != null && range.MinVersion.IsSemVer2())
                        {
                            return(true);
                        }

                        if (range.MaxVersion != null && range.MaxVersion.IsSemVer2())
                        {
                            return(true);
                        }
                    }
                }
            }


            return(false);
        }
Ejemplo n.º 2
0
 public static V2FeedPackageInfo ToV2FeedPackageInfo(
     this NuspecReader reader, PackageDerivedData packageDerivedData, string downloadUrl, long downloadCount)
 {
     return(new V2FeedPackageInfo(
                identity: new PackageIdentity(reader.GetId(), reader.GetVersion()),
                title: reader.GetTitle(),
                summary: reader.GetSummary(),
                description: reader.GetDescription(),
                authors: reader.GetAuthors().Split(','),
                owners: reader.GetOwners().Split(','),
                iconUrl: reader.GetIconUrl(),
                licenseUrl: reader.GetLicenseUrl(),
                projectUrl: reader.GetProjectUrl(),
                reportAbuseUrl: reader.GetProjectUrl(),
                tags: reader.GetTags(),
                created: packageDerivedData.Created,
                lastEdited: packageDerivedData.LastUpdated,
                published: packageDerivedData.LastUpdated,
                dependencies: DependencySetsAsString(reader.GetDependencyGroups()),
                requireLicenseAccept: reader.GetRequireLicenseAcceptance(),
                downloadUrl: downloadUrl,
                downloadCount: downloadCount.ToString(),
                packageHash: packageDerivedData.PackageHash,
                packageHashAlgorithm: packageDerivedData.PackageHashAlgorithm,
                minClientVersion: reader.GetMinClientVersion()
                ));
 }
Ejemplo n.º 3
0
        private static void AddDependencies(IEnumerable <LibraryDependency> dependencies, LockFileTargetLibrary lockFileLib, NuGetFramework framework, NuspecReader nuspec)
        {
            if (dependencies == null)
            {
                // AssetFallbackFramework does not apply to dependencies.
                // Convert it to a fallback framework if needed.
                var currentFramework = (framework as AssetTargetFallbackFramework)?.AsFallbackFramework() ?? framework;

                var dependencySet = nuspec
                                    .GetDependencyGroups()
                                    .GetNearest(currentFramework);

                if (dependencySet != null)
                {
                    var set = dependencySet.Packages;

                    if (set != null)
                    {
                        lockFileLib.Dependencies = set.AsList();
                    }
                }
            }
            else
            {
                // Filter the dependency set down to packages and projects.
                // Framework references will not be displayed
                lockFileLib.Dependencies = dependencies
                                           .Where(ld => ld.LibraryRange.TypeConstraintAllowsAnyOf(LibraryDependencyTarget.PackageProjectExternal))
                                           .Select(ld => new PackageDependency(ld.Name, ld.LibraryRange.VersionRange))
                                           .ToList();
            }
        }
Ejemplo n.º 4
0
        public static Package GetPackage(string nupkgPath)
        {
            var result = new Package();

            using (var packageFile = File.Open(nupkgPath, FileMode.Open, FileAccess.Read))
            {
                using (var packageReader = new PackageArchiveReader(packageFile))
                {
                    var manifestReader = new NuspecReader(packageReader.GetNuspec());
                    result.Authors                  = manifestReader.GetAuthors();
                    result.DependencySets           = manifestReader.GetDependencyGroups();
                    result.Description              = manifestReader.GetDescription();
                    result.Id                       = manifestReader.GetIdentity().Id;
                    result.LicenseUrl               = manifestReader.GetLicenseUrl();
                    result.ProjectUrl               = manifestReader.GetProjectUrl();
                    result.Summary                  = manifestReader.GetSummary();
                    result.Version                  = manifestReader.GetIdentity().Version;
                    result.RequireLicenseAcceptance = manifestReader.GetRequireLicenseAcceptance();
                    result.Files                    = packageReader.GetFiles()
                                                      .Where(x => x != "[Content_Types].xml" &&
                                                             x != "_rels/.rels" &&
                                                             !x.EndsWith(".nuspec") &&
                                                             !x.EndsWith(".psmdcp"))
                                                      .Select(x => x.Replace("/", "\\"))
                                                      .OrderBy(x => x).ToList();
                }
            }

            return(result);
        }
Ejemplo n.º 5
0
        public static Package CreatePackageObject(string packagePath)
        {
            List <PackageAsset> packageAssets = new List <PackageAsset>();
            Dictionary <NuGetFramework, List <PackageDependency> > packageDependencies = new Dictionary <NuGetFramework, List <PackageDependency> >();

            PackageArchiveReader nupkgReader  = new PackageArchiveReader(packagePath);
            NuspecReader         nuspecReader = nupkgReader.NuspecReader;

            string packageId = nuspecReader.GetId();
            string version   = nuspecReader.GetVersion().ToString();
            IEnumerable <PackageDependencyGroup> dependencyGroups = nuspecReader.GetDependencyGroups();

            foreach (var item in dependencyGroups)
            {
                packageDependencies.Add(item.TargetFramework, item.Packages.ToList());
            }

            var files = nupkgReader.GetFiles().ToList().Where(t => t.EndsWith(".dll")).Where(t => t.Contains(packageId + ".dll"));

            foreach (var file in files)
            {
                packageAssets.Add(ExtractAssetFromFile(file));
            }

            return(new Package(packageId, version, packageAssets, packageDependencies));
        }
        public async Task <IEnumerable <LibraryDependency> > GetDependencies(RemoteMatch match, NuGetFramework targetFramework)
        {
            using (var stream = await _source.OpenNuspecStreamAsync(new PackageInfo
            {
                Id = match.Library.Name,
                Version = match.Library.Version,
                ContentUri = match.Path
            }))
            {
                var nuspecReader = new NuspecReader(stream);
                var reducer      = new FrameworkReducer();

                var groups = nuspecReader.GetDependencyGroups()
                             .ToDictionary(g => new NuGetFramework(g.TargetFramework),
                                           g => g.Packages);


                var nearest = reducer.GetNearest(targetFramework, groups.Keys);

                if (nearest != null)
                {
                    return(groups[nearest].Select(p => new LibraryDependency
                    {
                        LibraryRange = new LibraryRange
                        {
                            Name = p.Id,
                            VersionRange = new NuGetVersionRange(p.VersionRange)
                        }
                    })
                           .ToList());
                }
            }

            return(Enumerable.Empty <LibraryDependency>());
        }
Ejemplo n.º 7
0
        private static void ReadPackage()
        {
            // This code region is referenced by the NuGet docs. Please update the docs if you rename the region
            // or move it to a different file.
            #region ReadPackage
            using FileStream inputStream      = new FileStream("MyPackage.nupkg", FileMode.Open);
            using PackageArchiveReader reader = new PackageArchiveReader(inputStream);
            NuspecReader nuspec = reader.NuspecReader;
            Console.WriteLine($"ID: {nuspec.GetId()}");
            Console.WriteLine($"Version: {nuspec.GetVersion()}");
            Console.WriteLine($"Description: {nuspec.GetDescription()}");
            Console.WriteLine($"Authors: {nuspec.GetAuthors()}");

            Console.WriteLine("Dependencies:");
            foreach (var dependencyGroup in nuspec.GetDependencyGroups())
            {
                Console.WriteLine($" - {dependencyGroup.TargetFramework.GetShortFolderName()}");
                foreach (var dependency in dependencyGroup.Packages)
                {
                    Console.WriteLine($"   > {dependency.Id} {dependency.VersionRange}");
                }
            }

            Console.WriteLine("Files:");
            foreach (var file in reader.GetFiles())
            {
                Console.WriteLine($" - {file}");
            }
            #endregion
        }
Ejemplo n.º 8
0
        public static NuGetDependencyInfo GetDependencyInfo(FileInfo nupkgPath)
        {
            if (!nupkgPath.Exists)
            {
                throw new FileNotFoundException(nupkgPath.FullName);
            }

            using (var stream = nupkgPath.OpenRead())
            {
                ZipFileSystem zip = new ZipFileSystem(stream);

                using (PackageReader packageReader = new PackageReader(zip))
                {
                    using (var nuspecStream = packageReader.GetNuspec())
                    {
                        NuspecReader reader = new NuspecReader(nuspecStream);

                        NuGetPackageId package = CreateIdentity(reader, nupkgPath.FullName);

                        List <NuGetDependencyGroup> dependencyGroups = new List <NuGetDependencyGroup>();

                        foreach (var depGroup in reader.GetDependencyGroups())
                        {
                            FrameworkName framework = Utilities.GetFrameworkName(depGroup.TargetFramework);

                            NuGetDependency[] dependencies = depGroup.Packages.Select(d => new NuGetDependency(d.Id, VersionRange.Parse(d.VersionRange))).ToArray();

                            dependencyGroups.Add(new NuGetDependencyGroup(framework, dependencies));
                        }

                        return(new NuGetDependencyInfo(package, dependencyGroups));
                    }
                }
            }
        }
Ejemplo n.º 9
0
        private List <BaGetPackageDependency> GetDependencies(NuspecReader nuspec)
        {
            var dependencies = new List <BaGetPackageDependency>();

            foreach (var group in nuspec.GetDependencyGroups())
            {
                var targetFramework = group.TargetFramework.GetShortFolderName();

                if (!group.Packages.Any())
                {
                    dependencies.Add(new BaGetPackageDependency
                    {
                        Id              = null,
                        VersionRange    = null,
                        TargetFramework = targetFramework,
                    });
                }

                foreach (var dependency in group.Packages)
                {
                    dependencies.Add(new BaGetPackageDependency
                    {
                        Id              = dependency.Id,
                        VersionRange    = dependency.VersionRange?.ToString(),
                        TargetFramework = targetFramework,
                    });
                }
            }

            return(dependencies);
        }
        private IEnumerable <LibraryDependency> GetDependencies(NuspecReader nuspecReader, NuGetFramework targetFramework)
        {
            var dependencies = NuGetFrameworkUtility.GetNearest(nuspecReader.GetDependencyGroups(),
                                                                targetFramework,
                                                                item => item.TargetFramework);

            return(GetDependencies(targetFramework, dependencies));
        }
 public static PackageMetadata FromNuspecReader(NuspecReader nuspecReader)
 {
     return(new PackageMetadata(
                nuspecReader.GetMetadata().ToDictionary(kvp => kvp.Key, kvp => kvp.Value),
                nuspecReader.GetDependencyGroups(),
                nuspecReader.GetFrameworkReferenceGroups()
                ));
 }
Ejemplo n.º 12
0
        public void NuspecReaderTests_DependencyGroups()
        {
            NuspecReader reader = GetReader(BasicNuspec);

            var dependencies = reader.GetDependencyGroups().ToList();

            Assert.Equal(2, dependencies.Count);
        }
Ejemplo n.º 13
0
        public void NuspecReaderTests_EmptyGroups()
        {
            NuspecReader reader = GetReader(EmptyGroups);

            var dependencies = reader.GetDependencyGroups().ToList();
            var references   = reader.GetReferenceGroups().ToList();

            Assert.Equal(2, dependencies.Count);
            Assert.Equal(2, references.Count);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Gets package metadata from a the provided <see cref="NuspecReader"/> instance.
 /// </summary>
 /// <param name="nuspecReader">The <see cref="NuspecReader"/> instance used to read the <see cref="PackageMetadata"/></param>
 /// <param name="strict">
 /// Whether or not to be strict when reading the <see cref="NuspecReader"/>. This should be <code>true</code>
 /// on initial ingestion but false when a package that has already been accepted is being processed.</param>
 /// <exception cref="PackagingException">
 /// We default to use a strict version-check on dependency groups.
 /// When an invalid dependency version range is detected, a <see cref="PackagingException"/> will be thrown.
 /// </exception>
 public static PackageMetadata FromNuspecReader(NuspecReader nuspecReader, bool strict)
 {
     return(new PackageMetadata(
                nuspecReader.GetMetadata().ToDictionary(kvp => kvp.Key, kvp => kvp.Value),
                nuspecReader.GetDependencyGroups(useStrictVersionCheck: strict),
                nuspecReader.GetFrameworkReferenceGroups(),
                nuspecReader.GetPackageTypes(),
                nuspecReader.GetMinClientVersion()
                ));
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Gets package metadata from a the provided <see cref="NuspecReader"/> instance.
        /// </summary>
        /// <param name="nuspecReader">The <see cref="NuspecReader"/> instance used to read the <see cref="PackageMetadata"/></param>
        /// <param name="strict">
        /// Whether or not to be strict when reading the <see cref="NuspecReader"/>. This should be <code>true</code>
        /// on initial ingestion but false when a package that has already been accepted is being processed.</param>
        /// <exception cref="PackagingException">
        /// We default to use a strict version-check on dependency groups.
        /// When an invalid dependency version range is detected, a <see cref="PackagingException"/> will be thrown.
        /// </exception>
        public static PackageMetadata FromNuspecReader(NuspecReader nuspecReader, bool strict)
        {
            var strictNuspecReader = new StrictNuspecReader(nuspecReader.Xml);
            var metadataLookup     = strictNuspecReader.GetMetadataLookup();

            if (strict)
            {
                var duplicates = metadataLookup
                                 .Where(g => g.Count() > 1)
                                 .Select(g => g.Key)
                                 .ToList();

                if (duplicates.Any())
                {
                    throw new PackagingException(string.Format(
                                                     CoreStrings.Manifest_DuplicateMetadataElements,
                                                     string.Join("', '", duplicates)));
                }
            }

            // Reject invalid metadata element names. Today this only rejects element names that collide with
            // properties generated downstream.
            var metadataKeys = new HashSet <string>(metadataLookup.Select(g => g.Key));

            metadataKeys.IntersectWith(RestrictedMetadataElements);
            if (metadataKeys.Any())
            {
                throw new PackagingException(string.Format(
                                                 CoreStrings.Manifest_InvalidMetadataElements,
                                                 string.Join("', '", metadataKeys.OrderBy(x => x))));
            }

            // Reject non-boolean values for boolean metadata.
            foreach (var booleanName in BooleanMetadataElements)
            {
                foreach (var unparsedBoolean in metadataLookup[booleanName])
                {
                    if (!bool.TryParse(unparsedBoolean, out var parsedBoolean))
                    {
                        throw new PackagingException(string.Format(
                                                         CoreStrings.Manifest_InvalidBooleanMetadata,
                                                         booleanName));
                    }
                }
            }

            return(new PackageMetadata(
                       nuspecReader.GetMetadata().ToDictionary(kvp => kvp.Key, kvp => kvp.Value),
                       nuspecReader.GetDependencyGroups(useStrictVersionCheck: strict),
                       nuspecReader.GetFrameworkReferenceGroups(),
                       nuspecReader.GetPackageTypes(),
                       nuspecReader.GetMinClientVersion(),
                       nuspecReader.GetRepositoryMetadata(),
                       nuspecReader.GetLicenseMetadata()));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Read dependency info from a nuspec.
        /// </summary>
        /// <remarks>This also verifies minClientVersion.</remarks>
        protected static FindPackageByIdDependencyInfo GetDependencyInfo(NuspecReader reader)
        {
            // Since this is the first place a package is read after selecting it as the best version
            // check the minClientVersion here to verify we are okay to read this package.
            MinClientVersionUtility.VerifyMinClientVersion(reader);

            // Create dependency info
            return(new FindPackageByIdDependencyInfo(
                       reader.GetDependencyGroups(),
                       reader.GetFrameworkReferenceGroups()));
        }
Ejemplo n.º 17
0
        public async Task RunAsync(string packageFilepath, string outputPath)
        {
            var packageFilename = new FileInfo(packageFilepath).Name;

            if (_packagesChecked.Contains(packageFilename))
            {
                return;
            }
            _packagesChecked.Add(packageFilename);

            using var zipFile = ZipFile.OpenRead(packageFilepath);

            var nuspec = zipFile.Entries
                         .SingleOrDefault(e => e.FullName.EndsWith(".nuspec"));

            if (nuspec == null)
            {
                Console.WriteLine($"ERROR: Package {zipFile.ToString()} does not contain a nuspec file.");
                return;
            }

            Directory.CreateDirectory(outputPath);

            await using var stream = nuspec.Open();
            var reader = new NuspecReader(stream);
            var groups = reader.GetDependencyGroups().ToList();

            foreach (var group in groups)
            {
                foreach (var package in group.Packages)
                {
                    var version        = package.VersionRange.ToShortString();
                    var url            = $"https://www.nuget.org/api/v2/package/{package.Id}/{version}";
                    var filename       = $"{package.Id}.{version}.nupkg";
                    var outputFilepath = Path.Combine(outputPath, filename);

                    try
                    {
                        if (!File.Exists(outputFilepath))
                        {
                            Console.WriteLine($"{packageFilename} GET {url}");
                            await new WebClient().DownloadFileTaskAsync(url, outputFilepath);
                        }
                    }
                    catch (WebException wex)
                    {
                        Console.WriteLine($"ERROR: {wex.Message}");
                        return;
                    }

                    await RunAsync(outputFilepath, outputPath);
                }
            }
        }
Ejemplo n.º 18
0
        public void NuspecReaderTests_UnsupportedDependencyGroups()
        {
            NuspecReader reader = GetReader(UnknownDependencyGroupsNuspec);

            // verify we can handle multiple unsupported dependency groups gracefully
            var dependencies = reader.GetDependencyGroups().ToList();

            // unsupported frameworks remain ungrouped
            Assert.Equal(5, dependencies.Count);

            Assert.Equal(4, dependencies.Where(g => g.TargetFramework == NuGetFramework.UnsupportedFramework).Count());
        }
Ejemplo n.º 19
0
        public void NuspecReaderTests_DependencyWithSingleIncludeExclude()
        {
            // Arrange
            NuspecReader reader = GetReader(IncludeExcludeNuspec);

            // Act
            var group      = reader.GetDependencyGroups().Single();
            var dependency = group.Packages.Single(package => package.Id == "packageA");

            // Assert
            Assert.Equal("all", string.Join("|", dependency.Include.OrderBy(s => s)));
            Assert.Equal("none", string.Join("|", dependency.Exclude.OrderBy(s => s)));
        }
Ejemplo n.º 20
0
        public void NuspecReaderTests_DependencyWithBlankExclude()
        {
            // Arrange
            NuspecReader reader = GetReader(IncludeExcludeNuspec);

            // Act
            var group      = reader.GetDependencyGroups().Single();
            var dependency = group.Packages.Single(package => package.Id == "packageD");

            // Assert bad flags stay as is
            Assert.Equal(0, dependency.Include.Count);
            Assert.Equal("a|b", string.Join("|", dependency.Exclude.OrderBy(s => s)));
        }
Ejemplo n.º 21
0
        public void NuspecReaderTests_DependencyEmptyAttributesForIncludeExclude()
        {
            // Arrange
            NuspecReader reader = GetReader(IncludeExcludeNuspec);

            // Act
            var group      = reader.GetDependencyGroups().Single();
            var dependency = group.Packages.Single(package => package.Id == "emptyValues");

            // Assert
            Assert.Equal(0, dependency.Include.Count);
            Assert.Equal(0, dependency.Exclude.Count);
        }
Ejemplo n.º 22
0
        public void NuspecReaderTests_DependencyWithMultipleExclude()
        {
            // Arrange
            NuspecReader reader = GetReader(IncludeExcludeNuspec);

            // Act
            var group      = reader.GetDependencyGroups().Single();
            var dependency = group.Packages.Single(package => package.Id == "packageC");

            // Assert
            Assert.Equal(0, dependency.Include.Count);
            Assert.Equal("compile|runtime", string.Join("|", dependency.Exclude.OrderBy(s => s)));
        }
Ejemplo n.º 23
0
        public static Package CreatePackageObject(string packagePath)
        {
            PackageArchiveReader nupkgReader  = new(packagePath);
            NuspecReader         nuspecReader = nupkgReader.NuspecReader;

            string packageId = nuspecReader.GetId();
            string version   = nuspecReader.GetVersion().ToString();

            NuGetFramework[] dependencyFrameworks = nuspecReader.GetDependencyGroups()
                                                    .Select(dg => dg.TargetFramework)
                                                    .Where(tfm => tfm != null)
                                                    .ToArray();
            IEnumerable <string> files = nupkgReader.GetFiles()?.Where(t => t.EndsWith(packageId + ".dll"));

            return(new Package(packageId, version, files, dependencyFrameworks));
        }
Ejemplo n.º 24
0
        private static Package CreatePackage(PackageArchiveReader packageReader, RuntimeGraph runtimeGraph)
        {
            NuspecReader nuspecReader = packageReader.NuspecReader;
            string       packageId    = nuspecReader.GetId();
            string       version      = nuspecReader.GetVersion().ToString();
            IEnumerable <PackageDependencyGroup> dependencyGroups = nuspecReader.GetDependencyGroups();

            Dictionary <NuGetFramework, IEnumerable <PackageDependency> > packageDependencies = new Dictionary <NuGetFramework, IEnumerable <PackageDependency> >();

            foreach (PackageDependencyGroup item in dependencyGroups)
            {
                packageDependencies.Add(item.TargetFramework, item.Packages);
            }

            return(new Package(packageId, version, packageReader.GetFiles()?.Where(t => t.EndsWith(packageId + ".dll")), packageDependencies, runtimeGraph));
        }
Ejemplo n.º 25
0
        internal static IEnumerable <(string PackageName, VersionRange PackageVersion)> GetNuspecDependencies(string nuspecFilePath)
        {
            if (!NuGet.Packaging.PackageHelper.IsNuspec(nuspecFilePath))
            {
                throw new Exception();
            }

            using var fileStream = File.OpenRead(nuspecFilePath);
            var reader = new NuspecReader(fileStream);
            // var currentFramework = new NuGetFramework(FrameworkConstants.FrameworkIdentifiers.NetCore, FrameworkConstants.FrameworkIdentifiers.
            // var targetFramework = NuGetFramework.Parse(_targetFramework);
            // var dependencyGroup = NuGetFrameworkUtility.GetNearest(reader.GetDependencyGroups(), targetFramework);
            // var dependencyGroup = GetNearest(reader.GetDependencyGroups());
            var dependencyGroup = reader.GetDependencyGroups().Single();

            return(dependencyGroup.Packages.Select(package => (package.Id, package.VersionRange)));
        }
Ejemplo n.º 26
0
        public ServerPackage(NuspecReader package, PackageDerivedData packageDerivedData)
        {
            Id         = package.GetId();
            Version    = package.GetVersion();
            Title      = package.GetTitle();
            Authors    = package.GetAuthors();
            Owners     = package.GetOwners();
            IconUrl    = package.GetIconUrl();
            LicenseUrl = package.GetLicenseUrl();
            ProjectUrl = package.GetProjectUrl();
            RequireLicenseAcceptance = package.GetRequireLicenseAcceptance();
            DevelopmentDependency    = package.GetDevelopmentDependency();
            Description             = package.GetDescription();
            Summary                 = package.GetSummary();
            ReleaseNotes            = package.GetReleaseNotes();
            Language                = package.GetLanguage();
            Tags                    = package.GetTags();
            Copyright               = package.GetCopyright();
            MinClientVersion        = package.GetMinClientVersion();
            ReportAbuseUrl          = null;
            DownloadCount           = 0;
            SemVer1IsAbsoluteLatest = false;
            SemVer1IsLatest         = false;
            SemVer2IsAbsoluteLatest = false;
            SemVer2IsLatest         = false;
            //FIXME is this OK?
            Listed = true;

            IsSemVer2 = IsPackageSemVer2(package);

            _dependencySets = package.GetDependencyGroups().ToList();
            Dependencies    = _dependencySets.DependencySetsAsString();

            _supportedFrameworks = package.GetFrameworkReferenceGroups().Select(f => f.TargetFramework).ToList();
            SupportedFrameworks  = string.Join("|", _supportedFrameworks.Select(f => f.GetFrameworkString()));

            PackageSize          = packageDerivedData.PackageSize;
            PackageHash          = packageDerivedData.PackageHash;
            PackageHashAlgorithm = packageDerivedData.PackageHashAlgorithm;
            LastUpdated          = packageDerivedData.LastUpdated;
            Created  = packageDerivedData.Created;
            Path     = packageDerivedData.Path;
            FullPath = packageDerivedData.FullPath;
        }
Ejemplo n.º 27
0
        private static PackageDependencyGroup GetDependencyGroup(PackageIdentity package, NuGetFramework targetFramework)
        {
            var nuspecFile = Path.Combine(_globalPackagesPath, package.Id, package.Version.ToNormalizedString(), $"{package.Id}.nuspec");

            if (!NuGet.Packaging.PackageHelper.IsNuspec(nuspecFile))
            {
                throw new PackageException($"Could not locate the .nuspec file for package: {package}");
            }
            var reader           = new NuspecReader(nuspecFile);
            var dependencyGroups = reader.GetDependencyGroups();

            if (dependencyGroups.FirstOrDefault() != null)
            {
                var compatibleGroups = dependencyGroups.Where(dependencyGroup => NuGetFrameworkUtility.IsCompatibleWithFallbackCheck(targetFramework, dependencyGroup.TargetFramework));
                // TODO: how to select best match framework?
                return(compatibleGroups.First());
            }
            return(null);
        }
Ejemplo n.º 28
0
        public static NuGetDependencyInfo GetDependencyInfo(string folderPath)
        {
            NuspecReader reader = GetNuspec(folderPath);

            NuGetPackageId package = CreateIdentity(reader, folderPath);

            List <NuGetDependencyGroup> dependencyGroups = new List <NuGetDependencyGroup>();

            foreach (var depGroup in reader.GetDependencyGroups())
            {
                FrameworkName framework = Utilities.GetFrameworkName(depGroup.TargetFramework);

                NuGetDependency[] dependencies = depGroup.Packages.Select(d => new NuGetDependency(d.Id, VersionRange.Parse(d.VersionRange))).ToArray();

                dependencyGroups.Add(new NuGetDependencyGroup(framework, dependencies));
            }

            return(new NuGetDependencyInfo(package, dependencyGroups));
        }
Ejemplo n.º 29
0
        // Based off https://github.com/NuGet/NuGetGallery/blob/master/src/NuGetGallery.Core/SemVerLevelKey.cs
        private static SemVerLevel GetSemVerLevel(NuspecReader nuspec)
        {
            if (nuspec.GetVersion().IsSemVer2)
            {
                return(SemVerLevel.SemVer2);
            }

            foreach (var dependencyGroup in nuspec.GetDependencyGroups())
            {
                foreach (var dependency in dependencyGroup.Packages)
                {
                    if ((dependency.VersionRange.MinVersion != null && dependency.VersionRange.MinVersion.IsSemVer2) ||
                        (dependency.VersionRange.MaxVersion != null && dependency.VersionRange.MaxVersion.IsSemVer2))
                    {
                        return(SemVerLevel.SemVer2);
                    }
                }
            }

            return(SemVerLevel.Unknown);
        }
Ejemplo n.º 30
0
        private void ProcessDependencies(NuspecReader nuspec, out IEnumerable <ParsedDependencyInfo> dependencies, out SemVerLevel semVerLevel)
        {
            semVerLevel = SemVerLevel.SemVer_2_0_0;
            var deps = new List <ParsedDependencyInfo>();

            dependencies = deps;
            foreach (var depgroup in nuspec.GetDependencyGroups())
            {
                foreach (var dep in depgroup.Packages)
                {
                    deps.Add(new ParsedDependencyInfo
                    {
                        Framework      = depgroup.TargetFramework,
                        PackageId      = dep.Id,
                        MinVersion     = dep.VersionRange.MinVersion,
                        MaxVersion     = dep.VersionRange.MaxVersion,
                        IsMinInclusive = dep.VersionRange.IsMinInclusive,
                        IsMaxInclusive = dep.VersionRange.IsMaxInclusive
                    });
                }
            }
        }