Пример #1
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()
                ));
 }
Пример #2
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);
        }
Пример #3
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
        }
Пример #4
0
        private NuGetPackageInfo ReadPackageInformation(string packageLocation)
        {
            using Stream inputStream          = _environmentSettings.Host.FileSystem.OpenRead(packageLocation);
            using PackageArchiveReader reader = new PackageArchiveReader(inputStream);

            NuspecReader nuspec = reader.NuspecReader;

            return(new NuGetPackageInfo(
                       nuspec.GetAuthors(),
                       packageLocation,
                       null,
                       nuspec.GetId(),
                       nuspec.GetVersion().ToNormalizedString()));
        }
Пример #5
0
 private void ProcessNuspecContent(NuspecReader reader)
 {
     if (Specification.Id == null)
     {
         Update(reader.GetId(), (id) => Specification.Id = id);
     }
     UpdateUrl(reader.GetLicenseUrl(), url => Specification.LicenseUrl    = url, DEFAULT_LICENCE_URL);
     UpdateUrl(reader.GetProjectUrl(), url => Specification.ProjectUrl    = url, DEFAULT_PROJECT_URL);
     UpdateUrl(reader.GetIconUrl(), url => Specification.IconUrl          = url, DEFAULT_ICON_URL);
     UpdateList(reader.GetAuthors(), list => Specification.Authors        = list);
     UpdateList(reader.GetOwners(), list => Specification.Owners          = list);
     Update(reader.GetReleaseNotes(), notes => Specification.ReleaseNotes = notes, DEFAULT_RELEASE_NOTES);
     Update(reader.GetCopyright(), copyright => Specification.Copyright   = copyright);
     UpdateList(reader.GetTags(), list => Specification.Tags           = list, ' ', DEFAULT_TAGS);
     Update(reader.GetDescription(), desc => Specification.Description = desc);
 }
Пример #6
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;
        }
Пример #7
0
        public async Task <string> DownloadPackageAsync(string connectionID, RequestDownloadInfo requestInfo)
        {
            // cast
            RequestDownloadNuGetInfo info = (RequestDownloadNuGetInfo)requestInfo;

            // server response
            ServerResponse response = new ServerResponse()
            {
                payload = new Dictionary <string, string>()
            };

            string _outputDirectory = $"{_environment.ContentRootPath}/wwwroot/{_configuration.GetValue<string>("DownloadPath")}";

            // check if output directory exists
            if (!Directory.Exists(_outputDirectory))
            {
                Directory.CreateDirectory(_outputDirectory);
            }

            string connectionSubName   = $"nuget-{connectionID}-{DateTime.Now:yyyymmddHHmmss}";
            string connectionDirectory = $"{_outputDirectory}/{connectionSubName}";

            Directory.CreateDirectory(connectionDirectory);

            // send message
            response.payload.Clear();
            response.payload.Add("Resource", $"{connectionSubName} created.");
            await _downloadHubContext.Clients.Client(connectionID).Response(response);

            ILogger                 logger            = NullLogger.Instance;
            CancellationToken       cancellationToken = CancellationToken.None;
            SourceCacheContext      cache             = new SourceCacheContext();
            SourceRepository        repository        = Repository.Factory.GetCoreV3(info.repository);
            FindPackageByIdResource resource          = await repository.GetResourceAsync <FindPackageByIdResource>();

            // set all parent packages
            for (int i = 0; i < info.packageList.Count(); i++)
            {
                string packageId           = info.packageList.ElementAt(i).packageId;
                string packageVersionValue = info.packageList.ElementAt(i).packageVersion;

                NuGetVersion packageVersion = new NuGetVersion(packageVersionValue);
                PackageInfo  package        = new PackageInfo {
                    packageId = packageId, packageVersion = packageVersion
                };

                if (package.packageVersion != null)
                {
                    _downloadQueue.Enqueue(package);
                }
                else
                {
                    FloatRange floatRange = null;
                    if (info.preReleased == true)
                    {
                        // include pre-release
                        floatRange = new FloatRange(NuGetVersionFloatBehavior.AbsoluteLatest);
                    }
                    else
                    {
                        // released
                        floatRange = new FloatRange(NuGetVersionFloatBehavior.Major);
                    }
                    FloatRange   fr    = new FloatRange(NuGetVersionFloatBehavior.Major);
                    VersionRange range = new VersionRange(floatRange: fr);

                    package = await GetBestMatchPackageVersionsAsync(repository, packageId, range);
                }
                _downloadQueue.Enqueue(package);
            }

            // download counter
            int download_counter = 0;

            while (_downloadQueue.Count > 0)
            {
                PackageInfo package = _downloadQueue.Dequeue();

                string validFileName   = FileUtil.GetValidFileName(package.packageId);
                string packageFilePath = $"{connectionDirectory}/{validFileName}.{package.packageVersion}.nupkg";

                if (_cacheDownloadedFileName.Contains($"{package.packageId}-{package.packageVersion}"))
                {
                    continue;
                }
                else
                {
                    _cacheDownloadedFileName.Add($"{package.packageId}-{package.packageVersion}");
                }

                using FileStream packageStream = new FileStream(packageFilePath, FileMode.Create);

                await resource.CopyNupkgToStreamAsync(
                    package.packageId,
                    package.packageVersion,
                    packageStream,
                    cache,
                    logger,
                    cancellationToken);

                download_counter++;

                // starting
                if (download_counter == 1)
                {
                    // send message
                    response.payload.Clear();
                    response.payload.Add("DownloadCounter", $"starting...");
                    await _downloadHubContext.Clients.Client(connectionID).Response(response);
                }

                // check if send message is needed
                if (download_counter % MessageFrequency == 0)
                {
                    // send message
                    response.payload.Clear();
                    response.payload.Add("DownloadCounter", $"{download_counter}, {((float)download_counter / (float)(download_counter + _downloadQueue.Count)) * 100.0f}%");
                    await _downloadHubContext.Clients.Client(connectionID).Response(response);
                }

                Console.WriteLine($"Downloaded package {package.packageId} {package.packageVersion}");

                using PackageArchiveReader packageReader = new PackageArchiveReader(packageStream);
                NuspecReader nuspecReader = await packageReader.GetNuspecReaderAsync(cancellationToken);

                Console.WriteLine($"Tags: {nuspecReader.GetTags()}");
                Console.WriteLine($"Description: {nuspecReader.GetDescription()}");

                using PackageArchiveReader reader = new PackageArchiveReader(packageStream);
                NuspecReader nuspec = reader.NuspecReader;
                Console.WriteLine($"ID: {nuspec.GetId()}");
                Console.WriteLine($"Version: {nuspec.GetVersion()}");
                Console.WriteLine($"Description: {nuspec.GetDescription()}");
                Console.WriteLine($"Authors: {nuspec.GetAuthors()}");

                if (info.withDependency == false)
                {
                    Console.WriteLine("\nDependencies download is not need.");
                    continue;
                }

                Console.WriteLine("\nStart download dependencies:");
                foreach (var dependencyGroup in nuspec.GetDependencyGroups())
                {
                    Console.WriteLine($" - {dependencyGroup.TargetFramework.GetFrameworkString()}");

                    // check target framework
                    if (!info.targetFramework.Contains("all", StringComparer.InvariantCultureIgnoreCase) &&
                        !info.targetFramework.Contains(dependencyGroup.TargetFramework.GetFrameworkString(), StringComparer.InvariantCultureIgnoreCase))
                    {
                        Console.WriteLine($" -- {dependencyGroup.TargetFramework.GetFrameworkString()} not match target framework.");
                        continue;
                    }

                    foreach (var dependency in dependencyGroup.Packages)
                    {
                        Console.WriteLine($"   > {dependency.Id} {dependency.VersionRange}");

                        PackageInfo dependencyPackage = await GetBestMatchPackageVersionsAsync(repository, dependency.Id, dependency.VersionRange);

                        Console.WriteLine($"   -- best match version: {dependency.Id} {dependencyPackage.packageVersion}");
                        _downloadQueue.Enqueue(dependencyPackage);
                    }
                }
            }

            // send message
            response.payload.Clear();
            response.payload.Add("DownloadCounter", $"{download_counter}, {((float)download_counter / (float)(download_counter + _downloadQueue.Count)) * 100.0f}%");
            await _downloadHubContext.Clients.Client(connectionID).Response(response);

            string zipFileName = $"{_outputDirectory}/{connectionSubName}.zip";
            bool   result      = _compressService.CompressDirectory(connectionDirectory, zipFileName);

            if (result == true)
            {
                string readableSize = FileUtil.getFileHumanReadableSize(zipFileName);
                // send message
                response.payload.Clear();
                response.payload.Add("CompressStatus", $"compressed ok, file sieze: {readableSize}.");
                await _downloadHubContext.Clients.Client(connectionID).Response(response);
            }
            else
            {
                // send message
                response.payload.Clear();
                response.payload.Add("CompressStatus", $"compressed failed.");
                await _downloadHubContext.Clients.Client(connectionID).Response(response);
            }

            // delete directory
            Directory.Delete(connectionDirectory, true);

            return(connectionSubName);
        }
Пример #8
0
        public async Task DownloadPackageAsync()
        {
            // check if output directory exists
            if (!Directory.Exists(_outputDirectory))
            {
                Directory.CreateDirectory(_outputDirectory);
            }

            // set all parent packages
            for (int i = 0; i < _packageIdList.Count(); i++)
            {
                string packageId = _packageIdList.ElementAt(i);

                PackageInfo package = null;
                if (_packageVersionList != null && _packageVersionList.Count() > i)
                {
                    string       packageVersionValue = _packageVersionList.ElementAt(i);
                    NuGetVersion packageVersion      = new NuGetVersion(packageVersionValue);
                    package = new PackageInfo {
                        packageId = packageId, packageVersion = packageVersion
                    };
                    _downloadQueue.Enqueue(package);
                }
                else
                {
                    FloatRange floatRange = null;
                    if (_preReleased == true)
                    {
                        // include pre-release
                        floatRange = new FloatRange(NuGetVersionFloatBehavior.AbsoluteLatest);
                    }
                    else
                    {
                        // released
                        floatRange = new FloatRange(NuGetVersionFloatBehavior.Major);
                    }
                    FloatRange   fr    = new FloatRange(NuGetVersionFloatBehavior.Major);
                    VersionRange range = new VersionRange(floatRange: fr);

                    package = await GetBestMatchPackageVersionsAsync(packageId, range);
                }
                _downloadQueue.Enqueue(package);
            }

            cancellationToken = CancellationToken.None;
            FindPackageByIdResource resource = await repository.GetResourceAsync <FindPackageByIdResource>();

            while (_downloadQueue.Count > 0)
            {
                PackageInfo package = _downloadQueue.Dequeue();

                string packageFilePath = $"{_outputDirectory}/{package.packageId}.{package.packageVersion}.nupkg";

                if (_cacheDownloadedFileName.Contains(packageFilePath))
                {
                    continue;
                }
                else
                {
                    _cacheDownloadedFileName.Add(packageFilePath);
                }

                using FileStream packageStream = new FileStream(packageFilePath, FileMode.Create);

                await resource.CopyNupkgToStreamAsync(
                    package.packageId,
                    package.packageVersion,
                    packageStream,
                    cache,
                    logger,
                    cancellationToken);

                Console.WriteLine($"Downloaded package {package.packageId} {package.packageVersion}");

                using PackageArchiveReader packageReader = new PackageArchiveReader(packageStream);
                NuspecReader nuspecReader = await packageReader.GetNuspecReaderAsync(cancellationToken);

                Console.WriteLine($"Tags: {nuspecReader.GetTags()}");
                Console.WriteLine($"Description: {nuspecReader.GetDescription()}");

                using PackageArchiveReader reader = new PackageArchiveReader(packageStream);
                NuspecReader nuspec = reader.NuspecReader;
                Console.WriteLine($"ID: {nuspec.GetId()}");
                Console.WriteLine($"Version: {nuspec.GetVersion()}");
                Console.WriteLine($"Description: {nuspec.GetDescription()}");
                Console.WriteLine($"Authors: {nuspec.GetAuthors()}");

                if (_withDependency == false)
                {
                    Console.WriteLine("\nDependencies download is not need.");
                    continue;
                }

                Console.WriteLine("\nDependencies:");
                foreach (var dependencyGroup in nuspec.GetDependencyGroups())
                {
                    Console.WriteLine($" - {dependencyGroup.TargetFramework.GetFrameworkString()}");

                    // check target framework
                    if (!_targetFramework.Contains("all", StringComparer.InvariantCultureIgnoreCase) &&
                        !_targetFramework.Contains(dependencyGroup.TargetFramework.GetFrameworkString(), StringComparer.InvariantCultureIgnoreCase))
                    {
                        Console.WriteLine($" -- {dependencyGroup.TargetFramework.GetFrameworkString()} not match target framework.");
                        continue;
                    }

                    foreach (var dependency in dependencyGroup.Packages)
                    {
                        Console.WriteLine($"   > {dependency.Id} {dependency.VersionRange}");

                        PackageInfo dependencyPackage = await GetBestMatchPackageVersionsAsync(dependency.Id, dependency.VersionRange);

                        Console.WriteLine($"   -- best match version: {dependencyPackage.packageVersion}");
                        _downloadQueue.Enqueue(dependencyPackage);
                    }
                }
            }
        }