예제 #1
0
        public Library GetLibrary(LibraryRange libraryRange, NuGetFramework targetFramework)
        {
            var package = FindCandidate(libraryRange.Name, libraryRange.VersionRange);

            if (package != null)
            {
                NuspecReader nuspecReader = null;
                using (var stream = File.OpenRead(package.ManifestPath))
                {
                    nuspecReader = new NuspecReader(stream);
                }

                var description = new Library
                    {
                        LibraryRange = libraryRange,
                        Identity = new LibraryIdentity
                            {
                                Name = package.Id,
                                Version = package.Version,
                                Type = LibraryTypes.Package
                            },
                        Path = package.ManifestPath,
                        Dependencies = GetDependencies(nuspecReader, targetFramework)
                    };

                description.Items["package"] = package;
                description.Items["metadata"] = nuspecReader;

                return description;
            }

            return null;
        }
        public override Task<FindPackageByIdDependencyInfo> GetDependencyInfoAsync(string id, NuGetVersion version, CancellationToken token)
        {
            var info = GetPackageInfo(id, version);
            FindPackageByIdDependencyInfo dependencyInfo = null;
            if (info != null)
            {
                var nuspecPath = Path.Combine(info.Path, $"{id}.nuspec");
                using (var stream = File.OpenRead(nuspecPath))
                {
                    NuspecReader nuspecReader;
                    try
                    {
                        nuspecReader = new NuspecReader(stream);
                    }
                    catch (XmlException ex)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, Strings.Protocol_PackageMetadataError, id + "." + version, _source);
                        throw new NuGetProtocolException(message, ex);
                    }
                    catch (PackagingException ex)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, Strings.Protocol_PackageMetadataError, id + "." + version, _source);
                        throw new NuGetProtocolException(message, ex);
                    }

                    dependencyInfo = GetDependencyInfo(nuspecReader);
                }
            }

            return Task.FromResult(dependencyInfo);
        }
예제 #3
0
        private IEnumerable<LibraryDependency> GetDependencies(NuspecReader nuspecReader, NuGetFramework targetFramework)
        {
            var dependencies = NuGetFrameworkUtility.GetNearest(nuspecReader.GetDependencyGroups(),
                targetFramework,
                item => item.TargetFramework);

            var frameworkAssemblies = NuGetFrameworkUtility.GetNearest(nuspecReader.GetFrameworkReferenceGroups(),
                targetFramework,
                item => item.TargetFramework);

            return GetDependencies(targetFramework, dependencies, frameworkAssemblies);
        }
 public static void CheckMinClientVersion(Stream packageStream, PackageIdentity packageIdentity)
 {
     var packageZipArchive = new ZipArchive(packageStream);
     var packageReader = new PackageReader(packageZipArchive);
     var nuspecReader = new NuspecReader(packageReader.GetNuspec());
     var packageMinClientVersion = nuspecReader.GetMinClientVersion();
     // validate that the current version of NuGet satisfies the minVersion attribute specified in the .nuspec
     if (Constants.NuGetSemanticVersion < packageMinClientVersion)
     {
         throw new NuGetVersionNotSatisfiedException(
             String.Format(CultureInfo.CurrentCulture, Strings.PackageMinVersionNotSatisfied, packageIdentity,
             packageMinClientVersion.ToNormalizedString(), Constants.NuGetSemanticVersion.ToNormalizedString()));
     }
 }
예제 #5
0
        public static IEnumerable<ValidationResult> Validate(Stream nuspecStream, out NuspecReader nuspecReader)
        {
            try
            {
                nuspecReader = new NuspecReader(nuspecStream);
                var rawMetadata = nuspecReader.GetMetadata();
                if (rawMetadata != null && rawMetadata.Any())
                {
                    return ValidateCore(PackageMetadata.FromNuspecReader(nuspecReader));
                }
            }
            catch (Exception ex)
            {
                nuspecReader = null;
                return new [] { new ValidationResult(ex.Message) };
            }

            return Enumerable.Empty<ValidationResult>();
        }
예제 #6
0
        /// <summary>
        /// A package is deemed to be a satellite package if it has a language property set, the id of the package is
        /// of the format [.*].[Language]
        /// and it has at least one dependency with an id that maps to the runtime package .
        /// </summary>
        public static bool IsSatellitePackage(NuspecReader nuspecReader, out PackageIdentity runtimePackageIdentity, out string packageLanguage)
        {
            // A satellite package has the following properties:
            //     1) A package suffix that matches the package's language, with a dot preceding it
            //     2) A dependency on the package with the same Id minus the language suffix
            //     3) The dependency can be found by Id in the repository (as its path is needed for installation)
            // Example: foo.ja-jp, with a dependency on foo

            var packageId = nuspecReader.GetId();
            packageLanguage = nuspecReader.GetLanguage();

            if (!String.IsNullOrEmpty(packageLanguage)
                && packageId.EndsWith('.' + packageLanguage, StringComparison.OrdinalIgnoreCase))
            {
                // The satellite pack's Id is of the format <Core-Package-Id>.<Language>. Extract the core package id using this.
                // Additionally satellite packages have a strict dependency on the core package
                var localruntimePackageId = packageId.Substring(0, packageId.Length - packageLanguage.Length - 1);

                foreach (var group in nuspecReader.GetDependencyGroups())
                {
                    foreach (var dependencyPackage in group.Packages)
                    {
                        if (dependencyPackage.Id.Equals(localruntimePackageId, StringComparison.OrdinalIgnoreCase)
                            && dependencyPackage.VersionRange != null
                            && dependencyPackage.VersionRange.MaxVersion == dependencyPackage.VersionRange.MinVersion
                            && dependencyPackage.VersionRange.IsMaxInclusive
                            && dependencyPackage.VersionRange.IsMinInclusive)
                        {
                            var runtimePackageVersion = new NuGetVersion(dependencyPackage.VersionRange.MinVersion.ToString());
                            runtimePackageIdentity = new PackageIdentity(dependencyPackage.Id, runtimePackageVersion);
                            return true;
                        }
                    }
                }
            }

            runtimePackageIdentity = null;
            return false;
        }
        public static IVsPackageMetadata CreateMetadata(string nupkgPath, PackageIdentity package)
        {
            IEnumerable<string> authors = Enumerable.Empty<string>();
            string description = string.Empty;
            string title = package.Id;
            string installPath = string.Empty;

            try
            {
                // installPath is the nupkg path
                FileInfo file = new FileInfo(nupkgPath);
                installPath = file.Directory.FullName;
                PackageReader reader = new PackageReader(file.OpenRead());

                using (var nuspecStream = reader.GetNuspec())
                {
                    NuspecReader nuspec = new NuspecReader(nuspecStream);

                    var metadata = nuspec.GetMetadata();

                    authors = GetNuspecValue(metadata, "authors").Split(',').ToArray();
                    title = GetNuspecValue(metadata, "title");
                    description = GetNuspecValue(metadata, "description");
                }
            }
            catch (Exception ex)
            {
                // ignore errors from reading the extra fields
                Debug.Fail(ex.ToString());
            }

            if (String.IsNullOrEmpty(title))
            {
                title = package.Id;
            }

            return new VsPackageMetadata(package, title, authors, description, installPath);
        }
예제 #8
0
 public virtual PackageIdentity GetIdentity()
 {
     return(NuspecReader.GetIdentity());
 }
예제 #9
0
 public virtual NuGetVersion GetMinClientVersion()
 {
     return(NuspecReader.GetMinClientVersion());
 }
예제 #10
0
        public static bool GetSatelliteFiles(Stream packageStream, PackageIdentity packageIdentity, PackagePathResolver packagePathResolver,
            out string language, out string runtimePackageDirectory, out IEnumerable<ZipArchiveEntry> satelliteFiles)
        {
            var zipArchive = new ZipArchive(packageStream);
            var packageReader = new PackageReader(zipArchive);
            var nuspecReader = new NuspecReader(packageReader.GetNuspec());

            PackageIdentity runtimePackageIdentity = null;
            string packageLanguage = null;
            if (IsSatellitePackage(nuspecReader, out runtimePackageIdentity, out packageLanguage))
            {
                // Now, we know that the package is a satellite package and that the runtime package is 'runtimePackageId'
                // Check, if the runtimePackage is installed and get the folder to copy over files

                var runtimePackageFilePath = packagePathResolver.GetInstalledPackageFilePath(runtimePackageIdentity);
                if (File.Exists(runtimePackageFilePath))
                {
                    runtimePackageDirectory = Path.GetDirectoryName(runtimePackageFilePath);
                    // Existence of the package file is the validation that the package exists
                    var libItemGroups = packageReader.GetLibItems();
                    var satelliteFileEntries = new List<ZipArchiveEntry>();
                    foreach (var libItemGroup in libItemGroups)
                    {
                        var satelliteFilesInGroup = libItemGroup.Items.Where(item => Path.GetDirectoryName(item).Split(Path.DirectorySeparatorChar)
                            .Contains(packageLanguage, StringComparer.OrdinalIgnoreCase));

                        foreach (var satelliteFile in satelliteFilesInGroup)
                        {
                            var zipArchiveEntry = zipArchive.GetEntry(satelliteFile);
                            if (zipArchiveEntry != null)
                            {
                                satelliteFileEntries.Add(zipArchiveEntry);
                            }
                        }
                    }

                    if (satelliteFileEntries.Count > 0)
                    {
                        language = packageLanguage;
                        satelliteFiles = satelliteFileEntries;
                        return true;
                    }
                }
            }

            language = null;
            runtimePackageDirectory = null;
            satelliteFiles = null;
            return false;
        }
예제 #11
0
        private void LoadNuSpecFile(string filePath)
        {
            NuSpecFilePath = Directory.GetFiles(System.IO.Path.GetDirectoryName(filePath), "*.nuspec", SearchOption.AllDirectories).FirstOrDefault();

            if (NuSpecFilePath != null)
            {
                using (var stream = File.Open(NuSpecFilePath, FileMode.Open))
                {
                    var reader = new NuspecReader(stream);

                    var packageId = reader.GetId();
                    if (packageId != null && packageId.ToLower() == "$id$")
                        packageId = Name;

                    NuGetPackageId = packageId;
                    NuGetPackageTitle = Name; 

                    var metadata = reader.GetMetadata().ToArray();
                    if (metadata.Any(p => p.Key == "title"))
                    {
                        var titlePair = metadata.SingleOrDefault(p => p.Key == "title");
                        NuGetPackageTitle = titlePair.Value;
                    }
                }
            }
        }
        private static NuGetPackageId CreateIdentity(NuspecReader reader, string folderPath)
        {
            NuGetPackageId package = null;
            NuGetVersion version = null;

            if (NuGetVersion.TryParse(reader.GetVersion(), out version))
            {
                package = new NuGetPackageId(reader.GetId(), version, folderPath);
            }
            else
            {
                throw new InvalidDataException("invalid version");
            }

            return package;
        }
예제 #13
0
        public static async Task <IEnumerable <string> > ExtractPackageAsync(
            PackageReaderBase packageReader,
            Stream packageStream,
            PackageIdentity packageIdentity,
            PackagePathResolver packagePathResolver,
            PackageExtractionContext packageExtractionContext,
            PackageSaveModes packageSaveMode,
            CancellationToken token)
        {
            if (packageStream == null)
            {
                throw new ArgumentNullException(nameof(packageStream));
            }

            if (packageIdentity == null)
            {
                throw new ArgumentNullException(nameof(packageIdentity));
            }

            if (packagePathResolver == null)
            {
                throw new ArgumentNullException(nameof(packagePathResolver));
            }

            // TODO: Need to handle PackageSaveMode
            // TODO: Support overwriting files also?
            var filesAdded = new List <string>();

            var nuspecReader = new NuspecReader(packageReader.GetNuspec());

            packageIdentity = nuspecReader.GetIdentity();

            var packageDirectoryInfo = Directory.CreateDirectory(packagePathResolver.GetInstallPath(packageIdentity));
            var packageDirectory     = packageDirectoryInfo.FullName;

            foreach (var file in packageReader.GetFiles().Where(file => PackageHelper.IsPackageFile(file, packageSaveMode)))
            {
                token.ThrowIfCancellationRequested();

                var targetPath = Path.Combine(packageDirectory, file);
                Directory.CreateDirectory(Path.GetDirectoryName(targetPath));

                using (var sourceStream = packageReader.GetStream(file))
                {
                    using (var targetStream = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 1024, useAsync: true))
                    {
                        await sourceStream.CopyToAsync(targetStream);
                    }
                }

                filesAdded.Add(file);
            }

            var nupkgFilePath = Path.Combine(packageDirectory, packagePathResolver.GetPackageFileName(packageIdentity));

            if (packageSaveMode.HasFlag(PackageSaveModes.Nupkg))
            {
                // During package extraction, nupkg is the last file to be created
                // Since all the packages are already created, the package stream is likely positioned at its end
                // Reset it
                if (packageStream.Position != 0)
                {
                    if (!packageStream.CanSeek)
                    {
                        throw new ArgumentException(Strings.PackageStreamShouldBeSeekable);
                    }

                    packageStream.Position = 0;
                }

                filesAdded.Add(await PackageHelper.CreatePackageFile(nupkgFilePath, packageStream, token));
            }

            // Now, copy satellite files unless requested to not copy them
            if (packageExtractionContext == null || packageExtractionContext.CopySatelliteFiles)
            {
                PackageIdentity runtimeIdentity;
                string          packageLanguage;
                var             isSatellitePackage = PackageHelper.IsSatellitePackage(nuspecReader, out runtimeIdentity, out packageLanguage);

                // Short-circuit this if the package is not a satellite package.
                if (isSatellitePackage)
                {
                    filesAdded.AddRange(await CopySatelliteFilesAsync(packageIdentity, packagePathResolver, packageSaveMode, token));
                }
            }

            return(filesAdded);
        }
        private List<CachedPackageInfo> GetPackageInfos(string id)
        {
            List<CachedPackageInfo> cachedPackageInfos;

            if (_packageInfoCache.TryGetValue(id, out cachedPackageInfos))
            {
                cachedPackageInfos = cachedPackageInfos.ToList();
            }

            var result = new List<CachedPackageInfo>();

            // packages\{packageId}.{version}.nupkg
            foreach (var nupkgInfo in GetNupkgFiles(_source, id))
            {
                var cachedPackageInfo = cachedPackageInfos?.FirstOrDefault(package => string.Equals(package.Path, nupkgInfo.FullName, StringComparison.OrdinalIgnoreCase));
                if (cachedPackageInfo != null
                    && cachedPackageInfo.LastWriteTimeUtc == nupkgInfo.LastWriteTimeUtc)
                {
                    result.Add(cachedPackageInfo);
                }

                using (var stream = nupkgInfo.OpenRead())
                {
                    var packageReader = new PackageReader(stream);
                    NuspecReader reader;
                    try
                    {
                        reader = new NuspecReader(packageReader.GetNuspec());
                    }
                    catch (XmlException ex)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, Strings.Protocol_PackageMetadataError, nupkgInfo.Name, _source);
                        throw new NuGetProtocolException(message, ex);
                    }
                    catch (PackagingException ex)
                    {
                        var message = string.Format(CultureInfo.CurrentCulture, Strings.Protocol_PackageMetadataError, nupkgInfo.Name, _source);
                        throw new NuGetProtocolException(message, ex);
                    }

                    if (string.Equals(reader.GetId(), id, StringComparison.Ordinal))
                    {
                        result.Add(new CachedPackageInfo { Path = nupkgInfo.FullName, Reader = reader });
                    }
                }
            }

            _packageInfoCache.TryAdd(id, result);

            return result;
        }
예제 #15
0
        public static async Task<IEnumerable<string>> ExtractPackageAsync(
            PackageReaderBase packageReader,
            Stream packageStream,
            PackageIdentity packageIdentity,
            PackagePathResolver packagePathResolver,
            PackageExtractionContext packageExtractionContext,
            PackageSaveModes packageSaveMode,
            CancellationToken token)
        {
            if (packageStream == null)
            {
                throw new ArgumentNullException(nameof(packageStream));
            }

            if (packageIdentity == null)
            {
                throw new ArgumentNullException(nameof(packageIdentity));
            }

            if (packagePathResolver == null)
            {
                throw new ArgumentNullException(nameof(packagePathResolver));
            }

            // TODO: Need to handle PackageSaveMode
            // TODO: Support overwriting files also?
            var filesAdded = new List<string>();

            var nuspecReader = new NuspecReader(packageReader.GetNuspec());
            packageIdentity = nuspecReader.GetIdentity();

            var packageDirectoryInfo = Directory.CreateDirectory(packagePathResolver.GetInstallPath(packageIdentity));
            var packageDirectory = packageDirectoryInfo.FullName;

            foreach (var file in packageReader.GetFiles().Where(file => PackageHelper.IsPackageFile(file, packageSaveMode)))
            {
                token.ThrowIfCancellationRequested();

                var targetPath = Path.Combine(packageDirectory, file);
                Directory.CreateDirectory(Path.GetDirectoryName(targetPath));

                using (var sourceStream = packageReader.GetStream(file))
                {
                    using (var targetStream = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 1024, useAsync: true))
                    {
                        await sourceStream.CopyToAsync(targetStream);
                    }
                }

                filesAdded.Add(file);
            }

            var nupkgFilePath = Path.Combine(packageDirectory, packagePathResolver.GetPackageFileName(packageIdentity));
            if (packageSaveMode.HasFlag(PackageSaveModes.Nupkg))
            {
                // During package extraction, nupkg is the last file to be created
                // Since all the packages are already created, the package stream is likely positioned at its end
                // Reset it
                if (packageStream.Position != 0)
                {
                    if (!packageStream.CanSeek)
                    {
                        throw new ArgumentException(Strings.PackageStreamShouldBeSeekable);
                    }

                    packageStream.Position = 0;

                }

                filesAdded.Add(await PackageHelper.CreatePackageFile(nupkgFilePath, packageStream, token));
            }

            // Now, copy satellite files unless requested to not copy them
            if (packageExtractionContext == null || packageExtractionContext.CopySatelliteFiles)
            {
                PackageIdentity runtimeIdentity;
                string packageLanguage;
                var isSatellitePackage = PackageHelper.IsSatellitePackage(nuspecReader, out runtimeIdentity, out packageLanguage);

                // Short-circuit this if the package is not a satellite package.
                if (isSatellitePackage)
                {
                    filesAdded.AddRange(await CopySatelliteFilesAsync(packageIdentity, packagePathResolver, packageSaveMode, token));
                }
            }

            return filesAdded;
        }
 public static void AssertReleaseNotes(this PackageArchiveReader package, string expectedReleaseNotes)
 {
     var nuspecReader = new NuspecReader(package.GetNuspec());
     var actualReleaseNotes = nuspecReader.GetMetadata().Single(x => x.Key == "releaseNotes").Value;
     Assert.That(actualReleaseNotes, Is.EqualTo(expectedReleaseNotes));
 }
 public static void AssertVersion(this PackageArchiveReader package, string expectedVersion)
 {
     var nuspecReader = new NuspecReader(package.GetNuspec());
     var actualVersion = nuspecReader.GetMetadata().Single(x => x.Key == "version").Value;
     Assert.That(actualVersion, Is.EqualTo(expectedVersion));
 }
예제 #18
0
 protected static FindPackageByIdDependencyInfo GetDependencyInfo(NuspecReader reader)
 {
     return new FindPackageByIdDependencyInfo(
         reader.GetDependencyGroups(),
         reader.GetFrameworkReferenceGroups());
 }
        bool TryReadPackageIdentity(string packageFile, out PackageIdentity packageIdentity)
        {
            packageIdentity = null;
            try
            {
                using (var reader = new PackageArchiveReader(new FileStream(packageFile, FileMode.Open, FileAccess.Read)))
                {
                    var nuspecReader = new NuspecReader(reader.GetNuspec());
                    packageIdentity = nuspecReader.GetIdentity();
                    return true;
                }
            }
            catch (Exception ex)
            {
               log.Warning(ex, "Could not read manifest from '{PackageFile:l}'", packageFile); 
            }

            return false;
        }
예제 #20
0
        public static async Task <IEnumerable <string> > ExtractPackageAsync(Stream packageStream, PackageIdentity packageIdentity,
                                                                             PackagePathResolver packagePathResolver,
                                                                             PackageExtractionContext packageExtractionContext,
                                                                             PackageSaveModes packageSaveMode,
                                                                             CancellationToken token)
        {
            List <string> filesAdded = new List <string>();

            if (packageStream == null)
            {
                throw new ArgumentNullException("packageStream");
            }

            if (!packageStream.CanSeek)
            {
                throw new ArgumentException(Strings.PackageStreamShouldBeSeekable);
            }

            if (packageIdentity == null)
            {
                throw new ArgumentNullException("packageIdentity");
            }

            if (packagePathResolver == null)
            {
                throw new ArgumentNullException("packagePathResolver");
            }

            // TODO: Need to handle PackageSaveMode
            // TODO: Support overwriting files also?
            long nupkgStartPosition = packageStream.Position;
            var  zipArchive         = new ZipArchive(packageStream);

            // default to non-legacy paths
            bool useLegacyPaths = packageExtractionContext == null ? false : packageExtractionContext.UseLegacyPackageInstallPath;

            var          packageReader            = new PackageReader(zipArchive);
            var          nuspecReader             = new NuspecReader(packageReader.GetNuspec());
            NuGetVersion packageVersionFromNuspec = nuspecReader.GetVersion();

            var    packageDirectoryInfo = Directory.CreateDirectory(packagePathResolver.GetInstallPath(new PackageIdentity(packageIdentity.Id, packageVersionFromNuspec), useLegacyPaths));
            string packageDirectory     = packageDirectoryInfo.FullName;

            filesAdded.AddRange(await PackageHelper.CreatePackageFiles(zipArchive.Entries, packageDirectory, packageSaveMode, token));

            string nupkgFilePath = Path.Combine(packageDirectory, packagePathResolver.GetPackageFileName(packageIdentity));

            if (packageSaveMode.HasFlag(PackageSaveModes.Nupkg))
            {
                // During package extraction, nupkg is the last file to be created
                // Since all the packages are already created, the package stream is likely positioned at its end
                // Reset it to the nupkgStartPosition
                packageStream.Seek(nupkgStartPosition, SeekOrigin.Begin);
                filesAdded.Add(await PackageHelper.CreatePackageFile(nupkgFilePath, packageStream, token));
            }

            // Now, copy satellite files unless requested to not copy them
            if (packageExtractionContext == null || packageExtractionContext.CopySatelliteFiles)
            {
                filesAdded.AddRange(await CopySatelliteFilesAsync(packageIdentity, packagePathResolver, packageSaveMode, token));
            }

            return(filesAdded);
        }
예제 #21
0
 public virtual IReadOnlyList <PackageType> GetPackageTypes()
 {
     return(NuspecReader.GetPackageTypes());
 }
        private static NuspecReader GetNuspec(string folderPath)
        {
            NuspecReader reader = null;

            string file = Directory.GetFiles(folderPath, PackagingConstants.NuspecExtensionFilter, SearchOption.TopDirectoryOnly).FirstOrDefault();

            if (String.IsNullOrEmpty(file))
            {
                throw new FileNotFoundException("unable to find nuspec");
            }

            using (Stream stream = File.OpenRead(file))
            {
                reader = new NuspecReader(stream);
            }

            return reader;
        }
예제 #23
0
        internal static LibraryIdentity CreateLibraryFromNupkg(string nupkgPath)
        {
            using (var fileStream = File.OpenRead(nupkgPath))
            {
                using (var archive = new ZipArchive(fileStream))
                {
                    foreach (var entry in archive.Entries)
                    {
                        if (!entry.Name.EndsWith(ManifestExtension, StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        using (var entryStream = entry.Open())
                        {
                            var reader = new NuspecReader(entryStream);
                            return new LibraryIdentity()
                                {
                                    Name = reader.GetId(),
                                    Version = reader.GetVersion(),
                                    Type = LibraryTypes.Package
                                };
                        }
                    }

                    throw new FormatException(
                        string.Format("{0} doesn't contain {1} entry", nupkgPath, ManifestExtension));
                }
            }
        }
예제 #24
0
        public static async Task<IEnumerable<string>> ExtractPackageAsync(
            Stream packageStream,
            PackageIdentity packageIdentity,
            PackagePathResolver packagePathResolver,
            PackageExtractionContext packageExtractionContext,
            PackageSaveModes packageSaveMode,
            CancellationToken token)
        {
            var filesAdded = new List<string>();
            if (packageStream == null)
            {
                throw new ArgumentNullException(nameof(packageStream));
            }

            if (!packageStream.CanSeek)
            {
                throw new ArgumentException(Strings.PackageStreamShouldBeSeekable);
            }

            if (packageIdentity == null)
            {
                throw new ArgumentNullException(nameof(packageIdentity));
            }

            if (packagePathResolver == null)
            {
                throw new ArgumentNullException(nameof(packagePathResolver));
            }

            // TODO: Need to handle PackageSaveMode
            // TODO: Support overwriting files also?
            var zipArchive = new ZipArchive(packageStream);

            var packageReader = new PackageReader(zipArchive);
            var nuspecReader = new NuspecReader(packageReader.GetNuspec());
            packageIdentity = nuspecReader.GetIdentity();

            var packageDirectoryInfo = Directory.CreateDirectory(packagePathResolver.GetInstallPath(packageIdentity));
            var packageDirectory = packageDirectoryInfo.FullName;

            filesAdded.AddRange(await PackageHelper.CreatePackageFiles(zipArchive.Entries, packageDirectory, packageSaveMode, token));

            var nupkgFilePath = Path.Combine(packageDirectory, packagePathResolver.GetPackageFileName(packageIdentity));
            if (packageSaveMode.HasFlag(PackageSaveModes.Nupkg))
            {
                // During package extraction, nupkg is the last file to be created
                // Since all the packages are already created, the package stream is likely positioned at its end
                // Reset it
                packageStream.Seek(0, SeekOrigin.Begin);
                filesAdded.Add(await PackageHelper.CreatePackageFile(nupkgFilePath, packageStream, token));
            }

            // Now, copy satellite files unless requested to not copy them
            if (packageExtractionContext == null
                || packageExtractionContext.CopySatelliteFiles)
            {
                filesAdded.AddRange(await CopySatelliteFilesAsync(packageIdentity, packagePathResolver, packageSaveMode, token));
            }

            return filesAdded;
        }
 public static void AssertTitle(this PackageArchiveReader package, string expectedTitle)
 {
     var nuspecReader = new NuspecReader(package.GetNuspec());
     var actualTitle = nuspecReader.GetMetadata().Single(x => x.Key == "title").Value;
     Assert.That(actualTitle , Is.EqualTo(expectedTitle));
 }
        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);
                    }
                }
            }
        }
예제 #27
0
 public static PackageMetadata FromNuspecReader(NuspecReader nuspecReader)
 {
     return new PackageMetadata(
         nuspecReader.GetMetadata().ToDictionary(kvp => kvp.Key, kvp => kvp.Value),
         nuspecReader.GetDependencyGroups(),
         nuspecReader.GetFrameworkReferenceGroups()
    );
 }
예제 #28
0
        private void LoadNuSpecFile(string filePath)
        {
            NuSpecFilePath = Directory.GetFiles(System.IO.Path.GetDirectoryName(filePath), "*.nuspec", SearchOption.AllDirectories).FirstOrDefault();

            if (NuSpecFilePath != null)
            {
                using (var stream = File.Open(NuSpecFilePath, FileMode.Open))
                {
                    var reader = new NuspecReader(stream);

                    var packageId = reader.GetId();
                    if (packageId != null && packageId.ToLower() == "$id$")
                        packageId = Name;

                    NuGetPackageId = packageId; 
                }
            }
        }