/// <summary>
        /// Attempts to find the package with given id and update its version number.
        /// </summary>
        /// <param name="packageId">Id of the package to change the version of</param>
        /// <param name="version">Version number to assign</param>
        /// <returns>
        /// True if package was found and the version number corresponds to a valid semantic version.
        /// False otherwise.
        /// </returns>
        /// <remarks>This method is safe to call simultaneously from multiple threads.</remarks>
        public bool TryUpdatePackage(string packageId, NuGetVersion version, out NuGetVersion?existingVersion)
        {
            if (!_packageXElements.TryGetValue(packageId, out XElement? xElement))
            {
                existingVersion = default;
                return(false);
            }

            lock (xElement)
            {
                string existingVersionStr = xElement.Attribute("version").Value;

                if (!NuGetVersion.TryParse(existingVersionStr, out existingVersion))
                {
                    return(false);
                }

                if (existingVersion >= version)
                {
                    // Package was found. But no version update was necessary
                    return(true);
                }

                // Update the version
                xElement.Attribute("version").Value = version.ToFullString();
            }

            // Store the document. Store a junk value (0) with it, because we have to.
            _modifiedDocuments[xElement.Document] = 0;
            return(true);
        }
Ejemplo n.º 2
0
 public static LeafInfo New(NuGetVersion version)
 {
     return(new LeafInfo(version, new RegistrationLeafItem
     {
         CatalogEntry = new RegistrationCatalogEntry
         {
             Version = version.ToFullString(),
         }
     }));
 }
Ejemplo n.º 3
0
        internal static string ToString(NuGetVersion version, NuGetVersionConversionFlags flags)
        {
            var versionString = ((flags & NuGetVersionConversionFlags.IncludeBuildMetadata) == 0)
                ? version.ToNormalizedString()
                : version.ToFullString();

            return(((flags & NuGetVersionConversionFlags.OriginalCasing) == 0)
                ? versionString.ToLowerInvariant()
                : versionString);
        }
Ejemplo n.º 4
0
        public void NuGetVersionParseStrict(string versionString)
        {
            // Arrange
            NuGetVersion semVer = null;

            NuGetVersion.TryParseStrict(versionString, out semVer);

            // Assert
            Assert.Equal <string>(versionString, semVer.ToFullString());
            Assert.Equal <string>(semVer.ToNormalizedString(), semVer.ToString());
        }
        private static ValidationResult ValidateDependencyVersion(NuGetVersion version)
        {
            if (version.HasMetadata)
            {
                return(new ValidationResult(string.Format(
                                                CultureInfo.CurrentCulture,
                                                CoreStrings.Manifest_InvalidDependencyVersion,
                                                version.ToFullString())));
            }

            return(ValidateVersionForLegacyClients(version));
        }
Ejemplo n.º 6
0
        public void AvailableVersionCompareNextTest()
        {
            NuGetVersion currentVersion = new NuGetVersion(
                VersionInfo.CurrentVersion.Major,
                VersionInfo.CurrentVersion.Minor,
                VersionInfo.CurrentVersion.Patch,
                VersionInfo.CurrentVersion.Revision + 1,
#pragma warning disable CS0436 // Type conflicts with imported type
                ThisAssembly.IsPublicRelease ? VersionInfo.CurrentVersion.ReleaseLabels :
#pragma warning restore CS0436 // Type conflicts with imported type
                VersionInfo.CurrentVersion.ReleaseLabels.Concat(new string[] { "g" + VersionInfo.CurrentVersion.Metadata }), string.Empty);
            NuGetVersion available = VersionInfo.GetBestAvailableVersion(new NuGetVersion[] { currentVersion }, true);

            Assert.IsNotNull(available);
            Assert.AreEqual(-1, VersionInfo.Compare(available.ToFullString()));
        }
Ejemplo n.º 7
0
        private async Task <string> ResolveNuGetVersion(PackageId packageId)
        {
            NuGetVersion resolvedVersion = null;

            if (!UpdatePackages)
            {
                resolvedVersion = await GetLatestMatchingVersion(packageId, _localRepositoryProvider.Repositories, _nuGetLogger);
            }

            if (resolvedVersion == null && _repositoryProvider.Repositories.Count > 0)
            {
                resolvedVersion = await GetLatestMatchingVersion(packageId, _repositoryProvider.Repositories, _nuGetLogger);
            }

            return(resolvedVersion == null ? null : resolvedVersion.ToFullString());
        }
Ejemplo n.º 8
0
            public void WillSendEmailToAllOwners(string version)
            {
                // Arrange
                var nugetVersion        = new NuGetVersion(version);
                var packageRegistration = new PackageRegistration
                {
                    Id     = "smangit",
                    Owners = new[]
                    {
                        new User {
                            EmailAddress = "*****@*****.**", NotifyPackagePushed = true
                        },
                        new User {
                            EmailAddress = "*****@*****.**", NotifyPackagePushed = true
                        }
                    }
                };
                var package = new Package
                {
                    Version             = version,
                    PackageRegistration = packageRegistration
                };

                packageRegistration.Packages.Add(package);

                // Act
                var messageService = TestableMessageService.Create(
                    GetService <AuthenticationService>(),
                    GetConfigurationService());
                var packageUrl       = $"https://localhost/packages/{packageRegistration.Id}/{nugetVersion.ToNormalizedString()}";
                var supportUrl       = $"https://localhost/packages/{packageRegistration.Id}/{nugetVersion.ToNormalizedString()}/ReportMyPackage";
                var emailSettingsUrl = "https://localhost/account";

                messageService.SendPackageAddedNotice(package, packageUrl, supportUrl, emailSettingsUrl);

                // Assert
                var message = messageService.MockMailSender.Sent.Last();

                Assert.Equal("*****@*****.**", message.To[0].Address);
                Assert.Equal("*****@*****.**", message.To[1].Address);
                Assert.Equal(TestGalleryNoReplyAddress, message.From);
                Assert.Contains($"[Joe Shmoe] Package published - {packageRegistration.Id} {nugetVersion.ToNormalizedString()}", message.Subject);
                Assert.Contains(
                    $"The package [{packageRegistration.Id} {nugetVersion.ToFullString()}]({packageUrl}) was just published on Joe Shmoe. If this was not intended, please [contact support]({supportUrl}).", message.Body);
            }
Ejemplo n.º 9
0
        private static ValidationResult ValidateVersion(NuGetVersion version)
        {
            if (version.IsSemVer2)
            {
                return(new ValidationResult(string.Format(
                                                CultureInfo.CurrentCulture,
                                                CoreStrings.Manifest_InvalidVersionSemVer200,
                                                version.ToFullString())));
            }
            else if (!version.IsValidVersionForLegacyClients())
            {
                return(new ValidationResult(string.Format(
                                                CultureInfo.CurrentCulture,
                                                CoreStrings.Manifest_InvalidVersion,
                                                version)));
            }

            return(null);
        }
Ejemplo n.º 10
0
        public void Constructor_DeserializesSemVer2Version()
        {
            // Arrange
            var cacheFile  = "{\"SchemaVersion\":\"3.0.0\",\"Packages\":[{\"Id\":\"" + PackageId + "\",\"Version\":\"" + SemVer2VersionString + "\"}]}";
            var fileSystem = new Mock <IFileSystem>();

            fileSystem
            .Setup(x => x.FileExists(CacheFileName))
            .Returns(true);
            fileSystem
            .Setup(x => x.OpenFile(CacheFileName))
            .Returns(() => new MemoryStream(Encoding.UTF8.GetBytes(cacheFile)));

            // Act
            var actual = new ServerPackageStore(fileSystem.Object, CacheFileName);

            // Assert
            Assert.Equal(1, actual.GetAll().Count());
            var package = actual.GetAll().First();

            Assert.Equal(SemVer2Version.ToString(), package.Version.ToString());
            Assert.Equal(SemVer2Version.ToFullString(), package.Version.ToFullString());
            Assert.Equal(SemVer2Version.ToNormalizedString(), package.Version.ToNormalizedString());
        }
Ejemplo n.º 11
0
        private void UpdateCatalogEntry(
            HiveType hive,
            string id,
            Protocol.Registration.RegistrationCatalogEntry catalogEntry,
            PackageDetailsCatalogLeaf packageDetails,
            NuGetVersion parsedVersion)
        {
            catalogEntry.Url     = packageDetails.Url;
            catalogEntry.Type    = JsonLdConstants.RegistrationLeafItemCatalogEntryType;
            catalogEntry.Authors = packageDetails.Authors ?? string.Empty;

            // Add the "registration" property to each package dependency.
            if (packageDetails.DependencyGroups != null)
            {
                catalogEntry.DependencyGroups = new List <RegistrationPackageDependencyGroup>();
                foreach (var group in packageDetails.DependencyGroups)
                {
                    var registrationGroup = new RegistrationPackageDependencyGroup
                    {
                        Url             = group.Url,
                        Type            = group.Type,
                        TargetFramework = group.TargetFramework,
                    };

                    catalogEntry.DependencyGroups.Add(registrationGroup);

                    if (group.Dependencies == null)
                    {
                        continue;
                    }

                    registrationGroup.Dependencies = new List <RegistrationPackageDependency>();

                    for (int i = 0; i < group.Dependencies.Count; i++)
                    {
                        var catalogDependency      = group.Dependencies[i];
                        var registrationDependency = new RegistrationPackageDependency
                        {
                            Url          = catalogDependency.Url,
                            Type         = catalogDependency.Type,
                            Id           = catalogDependency.Id,
                            Range        = catalogDependency.Range,
                            Registration = _urlBuilder.GetIndexUrl(hive, catalogDependency.Id),
                        };
                        registrationGroup.Dependencies.Add(registrationDependency);
                    }
                }
            }
            else
            {
                catalogEntry.DependencyGroups = null;
            }

            // Add the types to the deprecation.
            if (hive == HiveType.Legacy || hive == HiveType.Gzipped)
            {
                catalogEntry.Deprecation = null;
            }
            else
            {
                catalogEntry.Deprecation = packageDetails.Deprecation;
                if (catalogEntry.Deprecation != null)
                {
                    catalogEntry.Deprecation.Type = JsonLdConstants.PackageDeprecationType;
                    if (catalogEntry.Deprecation.AlternatePackage != null)
                    {
                        catalogEntry.Deprecation.AlternatePackage.Type = JsonLdConstants.AlternatePackageType;
                    }
                }
            }

            catalogEntry.Description = packageDetails.Description ?? string.Empty;

            if (!string.IsNullOrWhiteSpace(packageDetails.IconUrl) ||
                !string.IsNullOrWhiteSpace(packageDetails.IconFile))
            {
                catalogEntry.IconUrl = GetPackageIconUrl(id, packageDetails);
            }
            else
            {
                catalogEntry.IconUrl = string.Empty;
            }

            catalogEntry.PackageId         = packageDetails.PackageId ?? id;
            catalogEntry.Language          = packageDetails.Language ?? string.Empty;
            catalogEntry.LicenseExpression = packageDetails.LicenseExpression ?? string.Empty;

            if (!string.IsNullOrWhiteSpace(packageDetails.LicenseFile) ||
                !string.IsNullOrWhiteSpace(packageDetails.LicenseExpression))
            {
                // Use the package ID casing from this specific version, since license URLs do not exclusively use
                // lowercase package ID like icon URL. This is legacy behavior that can be revisited later. Gallery
                // supports case insensitive package IDs so it doesn't matter too much.
                catalogEntry.LicenseUrl = LicenseHelper.GetGalleryLicenseUrl(
                    catalogEntry.PackageId,
                    parsedVersion.ToNormalizedString(), _galleryBaseUrl);
            }
            else
            {
                catalogEntry.LicenseUrl = packageDetails.LicenseUrl ?? string.Empty;
            }

            catalogEntry.Listed                   = packageDetails.IsListed();
            catalogEntry.MinClientVersion         = packageDetails.MinClientVersion ?? string.Empty;
            catalogEntry.PackageContent           = GetPackageContentUrl(id, packageDetails);
            catalogEntry.ProjectUrl               = packageDetails.ProjectUrl ?? string.Empty;
            catalogEntry.Published                = packageDetails.Published;
            catalogEntry.RequireLicenseAcceptance = packageDetails.RequireLicenseAcceptance ?? false;
            catalogEntry.Summary                  = packageDetails.Summary ?? string.Empty;

            if (packageDetails.Tags != null && packageDetails.Tags.Count > 0)
            {
                catalogEntry.Tags = packageDetails.Tags;
            }
            else
            {
                catalogEntry.Tags = new List <string> {
                    string.Empty
                };
            }

            catalogEntry.Title   = packageDetails.Title ?? string.Empty;
            catalogEntry.Version = parsedVersion.ToFullString();

            if (hive == HiveType.SemVer2 &&
                packageDetails.Vulnerabilities != null &&
                packageDetails.Vulnerabilities.Count > 0)
            {
                catalogEntry.Vulnerabilities = packageDetails.Vulnerabilities.Select(v =>
                                                                                     new RegistrationPackageVulnerability()
                {
                    AdvisoryUrl = v.AdvisoryUrl,
                    Severity    = v.Severity
                }
                                                                                     ).ToList();
            }
            else
            {
                catalogEntry.Vulnerabilities = null;
            }
        }
Ejemplo n.º 12
0
            public static SdkResultBase GetSdkResult(SdkReference sdk, object nuGetVersion, SdkResolverContextBase context, SdkResultFactoryBase factory)
            {
                // Cast the NuGet version since the caller does not want to consume NuGet classes directly
                NuGetVersion parsedSdkVersion = (NuGetVersion)nuGetVersion;

                // Stores errors and warnings for the result
                ICollection <string> errors   = new List <string>();
                ICollection <string> warnings = new List <string>();

                // Load NuGet settings and a path resolver
                ISettings settings = Settings.LoadDefaultSettings(context.ProjectFilePath);

                FallbackPackagePathResolver fallbackPackagePathResolver = new FallbackPackagePathResolver(NuGetPathContext.Create(settings));

                string installedPath, installedVersion;

                // Attempt to find a package if its already installed
                if (!TryGetMSBuildSdkPackageInfo(fallbackPackagePathResolver, sdk.Name, parsedSdkVersion, out installedPath, out installedVersion))
                {
                    try
                    {
                        // Asynchronously run the restore without a commit which find the package on configured feeds, download, and unzip it without generating any other files
                        IReadOnlyList <RestoreResultPair> results = RestoreRunnerEx.RunWithoutCommit(
                            context.ProjectFilePath,
                            sdk.Name,
                            parsedSdkVersion.ToFullString(),
                            settings,
                            new NuGetSdkLogger(context.Logger, warnings, errors))
                                                                    .ConfigureAwait(continueOnCapturedContext: false)
                                                                    .GetAwaiter()
                                                                    .GetResult();

                        fallbackPackagePathResolver = new FallbackPackagePathResolver(NuGetPathContext.Create(settings));

                        // Look for a successful result, any errors are logged by NuGet
                        foreach (RestoreResult result in results.Select(i => i.Result).Where(i => i.Success))
                        {
                            // Find the information about the package that was installed.  In some cases, the version can be different than what was specified (like you specify 1.0 but get 1.0.0)
                            LibraryIdentity installedPackage = result.GetAllInstalled().FirstOrDefault(i => i.Name.Equals(sdk.Name));

                            if (installedPackage != null)
                            {
                                if (!TryGetMSBuildSdkPackageInfo(fallbackPackagePathResolver, installedPackage.Name, installedPackage.Version, out installedPath, out installedVersion))
                                {
                                    // This should never happen because we were told the package was successfully installed.
                                    // If we can't find it, we probably did something wrong with the NuGet API
                                    errors.Add(ResourceUtilities.FormatResourceString("CouldNotFindInstalledPackage", sdk));
                                }
                            }
                            else
                            {
                                // This should never happen because we were told the restore succeeded.
                                // If we can't find the package from GetAllInstalled(), we probably did something wrong with the NuGet API
                                errors.Add(ResourceUtilities.FormatResourceString("PackageWasNotInstalled", sdk, sdk.Name));
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        errors.Add(e.Message);
                    }
                }

                if (errors.Count == 0)
                {
                    return(factory.IndicateSuccess(path: installedPath, version: installedVersion, warnings: warnings));
                }

                return(factory.IndicateFailure(errors, warnings));
            }
Ejemplo n.º 13
0
 public static string ToFullStringSafe(this NuGetVersion self)
 {
     return(self != null?self.ToFullString() : string.Empty);
 }