public void VersionLength(string version) { // Arrange & Act var semVer = new NuGetVersion(version); Assert.Equal("2.0.0", semVer.ToNormalizedString()); }
public void Process(IndexReader indexReader, string readerName, int perSegmentDocumentNumber, int perIndexDocumentNumber, Document document, string id, NuGetVersion version) { // main index docid if (id == null || version == null) { return; } List<RegistrationEntry> versions; if (!_registrations.TryGetValue(id, out versions)) { versions = new List<RegistrationEntry>(); _registrations.Add(id, versions); } var entry = new RegistrationEntry(perIndexDocumentNumber, version, GetListed(document)); versions.Add(entry); }
/// <summary> /// Parses a version string using loose semantic versioning rules that allows 2-4 version components followed /// by an optional special version. /// </summary> public static bool TryParse(string value, out NuGetVersion version) { version = null; if (value != null) { Version systemVersion = null; // trim the value before passing it in since we not strict here var sections = ParseSections(value.Trim()); // null indicates the string did not meet the rules if (sections != null && !string.IsNullOrEmpty(sections.Item1)) { var versionPart = sections.Item1; if (versionPart.IndexOf('.') < 0) { // System.Version requires at least a 2 part version to parse. versionPart += ".0"; } if (Version.TryParse(versionPart, out systemVersion)) { // labels if (sections.Item2 != null && !sections.Item2.All(s => IsValidPart(s, false))) { return false; } // build metadata if (sections.Item3 != null && !IsValid(sections.Item3, true)) { return false; } var ver = NormalizeVersionValue(systemVersion); var originalVersion = value; if (originalVersion.IndexOf(' ') > -1) { originalVersion = value.Replace(" ", ""); } version = new NuGetVersion(version: ver, releaseLabels: sections.Item2, metadata: sections.Item3 ?? string.Empty, originalVersion: originalVersion); return true; } } } return false; }
public override bool IsInstalled(string packageId, NuGetVersion packageVersion) { NuGetTraceSources.CoreInteropInstalledPackagesList.Verbose("isinstalled", "IsInstalled? {0} {1}", packageId, packageVersion.ToNormalizedString()); return _localRepository.Exists( packageId, new SemanticVersion(packageVersion.Version, packageVersion.Release)); }
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); }
/// <summary> /// Creates a VersionRange with the given min and max. /// </summary> /// <param name="minVersion">Lower bound of the version range.</param> /// <param name="includeMinVersion">True if minVersion satisfies the condition.</param> /// <param name="maxVersion">Upper bound of the version range.</param> /// <param name="includeMaxVersion">True if maxVersion satisfies the condition.</param> /// <param name="includePrerelease">True if prerelease versions should satisfy the condition.</param> /// <param name="floatRange">The floating range subset used to find the best version match.</param> /// <param name="originalString">The original string being parsed to this object.</param> public VersionRange(NuGetVersion minVersion = null, bool includeMinVersion = true, NuGetVersion maxVersion = null, bool includeMaxVersion = false, bool? includePrerelease = null, FloatRange floatRange = null, string originalString = null) : base(minVersion, includeMinVersion, maxVersion, includeMaxVersion, includePrerelease) { _floatRange = floatRange; _originalString = originalString; }
public void Process(IndexReader indexReader, string readerName, int perSegmentDocumentNumber, int perIndexDocumentNumber, Document document, string id, NuGetVersion version) { HashSet<string> registrationOwners; if (id != null && _owners.TryGetValue(id, out registrationOwners)) { foreach (string registrationOwner in registrationOwners) { _knownOwners.Add(registrationOwner); DynamicDocIdSet ownerDocIdSet; if (_ownerTuples[readerName].TryGetValue(registrationOwner, out ownerDocIdSet)) { ownerDocIdSet.DocIds.Add(perSegmentDocumentNumber); } else { ownerDocIdSet = new DynamicDocIdSet(); ownerDocIdSet.DocIds.Add(perSegmentDocumentNumber); _ownerTuples[readerName].Add(registrationOwner, ownerDocIdSet); } } } }
public string GetLockFilePath(string packageId, NuGetVersion version, NuGetFramework framework) { return Path.Combine( GetBaseToolPath(packageId), version.ToNormalizedString(), framework.GetShortFolderName(), "project.lock.json"); }
public LocalPackageInfo(string packageId, NuGetVersion version, string path) { Id = packageId; Version = version; ExpandedPath = path; ManifestPath = Path.Combine(path, string.Format("{0}.nuspec", Id)); ZipPath = Path.Combine(path, string.Format("{0}.{1}.nupkg", Id, Version)); }
static PackageIdentity CreatePackageIdentity (string packageId, string packageVersion) { NuGetVersion nuGetVersion = null; if (packageVersion != null) { nuGetVersion = new NuGetVersion (packageVersion); } return new PackageIdentity (packageId, nuGetVersion); }
public UserAction(NuGetProjectActionType action, string packageId, NuGetVersion packageVersion) { Action = action; PackageId = packageId; if(packageVersion != null) { PackageIdentity = new PackageIdentity(packageId, packageVersion); } }
public PackageInstallationInfo(Project project, NuGetVersion version, bool enabled) { Project = project; _name = Project.Name; _selected = enabled; Version = version; Enabled = enabled; IsSolution = false; }
void CreatePackageReference ( string packageId = "Id", string packageVersion = "1.2.3", bool requireReinstallation = false) { var version = new NuGetVersion (packageVersion); var identity = new PackageIdentity (packageId, version); packageReference = new PackageReference (identity, null, true, false, requireReinstallation); }
public static PackageReference Clone( this PackageReference source, NuGetVersion version = null ) { return new PackageReference( new PackageIdentity( source.PackageIdentity.Id, version ?? source.PackageIdentity.Version ), source.TargetFramework, source.IsUserInstalled, source.IsDevelopmentDependency, source.RequireReinstallation, source.AllowedVersions ); }
/// <summary> /// Write a minimum client version to packages.config /// </summary> /// <param name="version">Minumum version of the client required to parse and use this file.</param> public void WriteMinClientVersion(NuGetVersion version) { if (_minClientVersion != null) { throw new PackagingException(String.Format(CultureInfo.InvariantCulture, "MinClientVersion already exists")); } _minClientVersion = version; }
/// <summary> /// Constructs the URI of a registration blob with a specific version /// </summary> public virtual Uri GetUri(string id, NuGetVersion version) { if (String.IsNullOrEmpty(id) || version == null) { throw new InvalidOperationException(); } return GetUri(new PackageIdentity(id, version)); }
public void Process(IndexReader indexReader, string readerName, int perSegmentDocumentNumber, int perIndexDocumentNumber, Document document, string id, NuGetVersion version) { _rankingBySegmentReaderName[readerName][perSegmentDocumentNumber] = GetRanking(_rankings, id); }
public override Task<Stream> GetNupkgStreamAsync(string id, NuGetVersion version, CancellationToken token) { var info = GetPackageInfo(id, version); if (info != null) { return Task.FromResult<Stream>(File.OpenRead(info.Path)); } return Task.FromResult<Stream>(null); }
public void Process(IndexReader indexReader, string readerName, int perSegmentDocumentNumber, int perIndexDocumentNumber, Document document, string id, NuGetVersion version) { _mapping[readerName][perSegmentDocumentNumber] = perIndexDocumentNumber; }
public void TestIsItemRangeRequiredTrue(string dependencyRangeString) { // Arrange NuGetVersion catalogItemLower = new NuGetVersion("1.0.0"); NuGetVersion catalogItemUpper = new NuGetVersion("2.0.0"); VersionRange dependencyRange = VersionRange.Parse(dependencyRangeString); // Act and Assert Assert.True(ResolverMetadataClientUtility.IsItemRangeRequired(dependencyRange, catalogItemLower, catalogItemUpper)); }
public void TestIsItemRangeRequiredFalse(string preFilterRangeString) { // Arrange NuGetVersion catalogItemLower = new NuGetVersion("1.0.0"); NuGetVersion catalogItemUpper = new NuGetVersion("2.0.0"); VersionRange preFilterRange = VersionRange.Parse(preFilterRangeString); // Act and Assert Assert.False(ResolverMetadataClientUtility.IsItemRangeRequired(preFilterRange, catalogItemLower, catalogItemUpper)); }
public LockFilePackageLibrary GetPackage(string id, NuGetVersion version) { LockFilePackageLibrary package; if (_packages.TryGetValue(Tuple.Create(id, version), out package)) { return package; } return null; }
public async Task ForceUninstall (string packageId, NuGetVersion packageVersion) { packageIdentity = new PackageIdentity (packageId, packageVersion); FilePath installPath = packagePathResolver.GetInstallPath (packageIdentity); RemoveReferences (installPath); using (var importRemover = new NuGetPackageForcedImportsRemover (installPath)) { await project.SaveAsync (); } }
private static Lazy<Task<IEnumerable<NuGetVersion>>> GetLazyVersionList(JObject package, bool includePrerelease, NuGetVersion topVersion) { return new Lazy<Task<IEnumerable<NuGetVersion>>>(() => { var versionList = GetVersionList(package, includePrerelease, topVersion); return Task.FromResult(versionList); }); }
public VersionForDisplay( NuGetVersion version, string additionalInfo) { Version = version; _additionalInfo = additionalInfo; _toString = string.IsNullOrEmpty(_additionalInfo) ? Version.ToNormalizedString() : _additionalInfo + " " + Version.ToNormalizedString(); }
public override Task<FindPackageByIdDependencyInfo> GetDependencyInfoAsync(string id, NuGetVersion version, CancellationToken token) { FindPackageByIdDependencyInfo dependencyInfo = null; var info = GetPackageInfo(id, version); if (info != null) { dependencyInfo = GetDependencyInfo(info.Reader); } return Task.FromResult(dependencyInfo); }
public void ParseVersionRangeParts(NuGetVersion min, NuGetVersion max, bool minInc, bool maxInc) { // Act var versionInfo = new VersionRange(min, minInc, max, maxInc); // Assert Assert.Equal(min, versionInfo.MinVersion, VersionComparer.Default); Assert.Equal(max, versionInfo.MaxVersion, VersionComparer.Default); Assert.Equal(minInc, versionInfo.IsMinInclusive); Assert.Equal(maxInc, versionInfo.IsMaxInclusive); }
public ServerPackageMetadata(PackageIdentity identity, string title, string summary, string description, IEnumerable<string> authors, Uri iconUrl, Uri licenseUrl, Uri projectUrl, IEnumerable<string> tags, DateTimeOffset? published, IEnumerable<PackageDependencyGroup> dependencySets, bool requireLicenseAcceptance, NuGetVersion minClientVersion, int downloadCount, int downloadCountForVersion, IEnumerable<string> owners, IEnumerable<string> packageTypes) : base(identity, title, summary, description, authors, iconUrl, licenseUrl, projectUrl, tags, published, dependencySets, requireLicenseAcceptance, minClientVersion) { _downloadCount = downloadCount; _downloadCountForVersion = downloadCountForVersion; _owners = owners == null ? new string[0] : owners.ToArray(); _packageTypes = packageTypes == null ? new string[0] : packageTypes.ToArray(); }
public void ParseVersionRangeToStringReParse(NuGetVersion min, NuGetVersion max, bool minInc, bool maxInc) { // Act var original = new VersionRange(min, minInc, max, maxInc); var versionInfo = VersionRange.Parse(original.ToString()); // Assert Assert.Equal(min, versionInfo.MinVersion, VersionComparer.Default); Assert.Equal(max, versionInfo.MaxVersion, VersionComparer.Default); Assert.Equal(minInc, versionInfo.IsMinInclusive); Assert.Equal(maxInc, versionInfo.IsMaxInclusive); }
public override Task<Stream> GetNupkgStreamAsync(string id, NuGetVersion version, CancellationToken token) { var info = GetPackageInfo(id, version); Stream result = null; if (info != null) { var packagePath = Path.Combine(info.Path, $"{id}.{version.ToString()}.nupkg"); result = File.OpenRead(packagePath); } return Task.FromResult(result); }
/// <summary> /// Creates a VersionRange with the given min and max. /// </summary> /// <param name="minVersion">Lower bound of the version range.</param> /// <param name="includeMinVersion">True if minVersion satisfies the condition.</param> /// <param name="maxVersion">Upper bound of the version range.</param> /// <param name="includeMaxVersion">True if maxVersion satisfies the condition.</param> /// <param name="includePrerelease">True if prerelease versions should satisfy the condition.</param> /// <param name="floatRange">The floating range subset used to find the best version match.</param> /// <param name="originalString">The original string being parsed to this object.</param> public VersionRange(NuGetVersion minVersion = null, bool includeMinVersion = true, NuGetVersion maxVersion = null, bool includeMaxVersion = false, bool?includePrerelease = null, FloatRange floatRange = null, string originalString = null) : base(minVersion, includeMinVersion, maxVersion, includeMaxVersion, includePrerelease) { _floatRange = floatRange; _originalString = originalString; }
public bool Execute() { var assembly = Assembly.GetEntryAssembly(); var packageId = "EBerzosa.Pundit"; var assemblyVersion = assembly.GetName().Version; var minVersion = new NuGet.Versioning.NuGetVersion(assemblyVersion.Major, 0, 0); var maxVersion = new NuGet.Versioning.NuGetVersion(assemblyVersion.Major + 1, 0, 0); var manifest = new PackageManifestRoot { PackageId = packageId, Framework = NuGet.Frameworks.NuGetFramework.AgnosticFramework, Version = new NuGet.Versioning.NuGetVersion(1, 0, 0, 0), Dependencies = { new PackageDependency(packageId, new NuGet.Versioning.VersionRange(minVersion, true, maxVersion)) { Scope = DependencyScope.Normal } } }; manifest.Validate(); _writer.BeginWrite().Text("Getting repositories..."); var scope = CacheReposOnly ? RepositoryScope.Cache : RepositoryScope.Any; var repos = _repositoryFactory.TryGetEnabledRepos(scope).ToArray(); if (repos.Length == 0) { _writer.Error(" no available repos").EndWrite(); return(false); } _writer.Text(" using repos:").EndWrite(); foreach (var repository in repos) { _writer.Info(repository.ToString()); } _writer.BeginWrite().Text("Resolving..."); var resolutionResult = _dependencyResolver.Resolve(manifest, repos, null); if (resolutionResult.ResolutionTable.HasConflicts) { _writer.Error(" failed").EndWrite() .Empty() .BeginWrite().Error("Could not resolve manifest due to conflicts...").EndWrite(); PrintConflicts(_dependencyResolver, resolutionResult); return(false); } _writer.Success(" ok").EndWrite(); if (DryRun) { return(true); } var currentPath = Path.GetDirectoryName(assembly.Location); if (!Install(resolutionResult, manifest, currentPath, out var oldVersion)) { return(true); } var oldPath = Path.Combine(currentPath, "old", DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + "_" + oldVersion); var updatePath = Path.Combine(currentPath, "lib"); if (Directory.Exists(oldPath)) { foreach (var file in Directory.EnumerateFiles(oldPath)) { File.Delete(file); } } else { Directory.CreateDirectory(oldPath); } foreach (var originalFile in Directory.EnumerateFiles(currentPath)) { if (Path.GetFileNameWithoutExtension(originalFile) == string.Empty) { continue; } File.Move(originalFile, Path.Combine(oldPath, Path.GetFileName(originalFile))); } foreach (var newFile in Directory.EnumerateFiles(updatePath)) { File.Move(newFile, Path.Combine(currentPath, Path.GetFileName(newFile))); } Directory.Delete(updatePath, false); return(true); }
/// <summary> /// Parses a version string using loose semantic versioning rules that allows 2-4 version components followed /// by an optional special version. /// </summary> public static bool TryParse(string value, out NuGetVersion version) { version = null; if (value != null) { Version systemVersion = null; // trim the value before passing it in since we not strict here ParseSections(value.Trim(), out string versionString, out string[] releaseLabels, out string buildMetadata); // null indicates the string did not meet the rules if (!string.IsNullOrEmpty(versionString)) { var versionPart = versionString; if (versionPart.IndexOf('.') < 0) { // System.Version requires at least a 2 part version to parse. versionPart += ".0"; } if (Version.TryParse(versionPart, out systemVersion)) { // labels if (releaseLabels != null) { for (int i = 0; i < releaseLabels.Length; i++) { if (!IsValidPart(releaseLabels[i], allowLeadingZeros: false)) { return(false); } } } // build metadata if (buildMetadata != null && !IsValid(buildMetadata, allowLeadingZeros: true)) { return(false); } var ver = NormalizeVersionValue(systemVersion); var originalVersion = value; if (originalVersion.IndexOf(' ') > -1) { originalVersion = value.Replace(" ", string.Empty); } version = new NuGetVersion(version: ver, releaseLabels: releaseLabels, metadata: buildMetadata ?? string.Empty, originalVersion: originalVersion); return(true); } } } return(false); }
/// <summary> /// Determines if a given version is better suited to the range than a current version. /// </summary> public bool IsBetter(NuGetVersion current, NuGetVersion considering) { if (ReferenceEquals(current, considering)) { return(false); } // null checks if (ReferenceEquals(considering, null)) { return(false); } // If the range contains only stable versions disallow prerelease versions if (!HasPrereleaseBounds && considering.IsPrerelease && _floatRange?.FloatBehavior != NuGetVersionFloatBehavior.Prerelease && _floatRange?.FloatBehavior != NuGetVersionFloatBehavior.AbsoluteLatest) { return(false); } if (!Satisfies(considering)) { // keep null over a value outside of the range return(false); } if (ReferenceEquals(current, null)) { return(true); } if (IsFloating) { // check if either version is in the floating range var curInRange = _floatRange.Satisfies(current); var conInRange = _floatRange.Satisfies(considering); if (curInRange && !conInRange) { // take the version in the range return(false); } else if (conInRange && !curInRange) { // take the version in the range return(true); } else if (curInRange && conInRange) { // prefer the highest one if both are in the range return(current < considering); } else { // neither are in range var curToLower = current < _floatRange.MinVersion; var conToLower = considering < _floatRange.MinVersion; if (curToLower && !conToLower) { // favor the version above the range return(true); } else if (!curToLower && conToLower) { // favor the version above the range return(false); } else if (!curToLower && !conToLower) { // favor the lower version if we are above the range return(current > considering); } else if (curToLower && conToLower) { // favor the higher version if we are below the range return(current < considering); } } } // Favor lower versions return(current > considering); }
/// <summary> /// Creates a range that is greater than or equal to the minVersion. /// </summary> /// <param name="minVersion">Lower bound of the version range.</param> public VersionRange(NuGetVersion minVersion) : this(minVersion, null) { }
/// <summary> /// Determines if a given version is better suited to the range than a current version. /// </summary> public bool IsBetter(NuGetVersion current, NuGetVersion considering) { if (Object.ReferenceEquals(current, considering)) { return(false); } // null checks if (Object.ReferenceEquals(considering, null)) { return(false); } if (!Satisfies(considering)) { // keep null over a value outside of the range return(false); } if (Object.ReferenceEquals(current, null)) { return(true); } if (IsFloating) { // check if either version is in the floating range bool curInRange = _floatRange.Satisfies(current); bool conInRange = _floatRange.Satisfies(considering); if (curInRange && !conInRange) { // take the version in the range return(false); } else if (conInRange && !curInRange) { // take the version in the range return(true); } else if (curInRange && conInRange) { // prefer the highest one if both are in the range return(current < considering); } else { // neither are in range bool curToLower = current < _floatRange.MinVersion; bool conToLower = considering < _floatRange.MinVersion; if (curToLower && !conToLower) { // favor the version above the range return(true); } else if (!curToLower && conToLower) { // favor the version above the range return(false); } else if (!curToLower && !conToLower) { // favor the lower version if we are above the range return(current > considering); } else if (curToLower && conToLower) { // favor the higher version if we are below the range return(current < considering); } } } // Favor lower versions return(current > considering); }
/// <summary> /// Creates a range that is greater than or equal to the minVersion with the given float behavior. /// </summary> /// <param name="minVersion">Lower bound of the version range.</param> public VersionRange(NuGetVersion minVersion, FloatRange floatRange) : this(minVersion, true, null, false, null, floatRange) { }
/// <summary> /// Create a floating range. /// </summary> /// <param name="floatBehavior">Section to float.</param> /// <param name="minVersion">Min version of the range.</param> public FloatRange(NuGetVersionFloatBehavior floatBehavior, NuGetVersion minVersion) : this(floatBehavior, minVersion, null) { }
/// <summary> /// True if the given version falls into the floating range. /// </summary> public bool Satisfies(NuGetVersion version) { if (version == null) { throw new ArgumentNullException(nameof(version)); } if (_floatBehavior == NuGetVersionFloatBehavior.AbsoluteLatest) { return(true); } if (_floatBehavior == NuGetVersionFloatBehavior.Major && !version.IsPrerelease) { return(true); } if (_minVersion != null) { // everything beyond this point requires a version if (_floatBehavior == NuGetVersionFloatBehavior.PrereleaseRevision) { // allow the stable version to match return(_minVersion.Major == version.Major && _minVersion.Minor == version.Minor && _minVersion.Patch == version.Patch && ((version.IsPrerelease && version.Release.StartsWith(_releasePrefix, StringComparison.OrdinalIgnoreCase)) || !version.IsPrerelease)); } else if (_floatBehavior == NuGetVersionFloatBehavior.PrereleasePatch) { // allow the stable version to match return(_minVersion.Major == version.Major && _minVersion.Minor == version.Minor && ((version.IsPrerelease && version.Release.StartsWith(_releasePrefix, StringComparison.OrdinalIgnoreCase)) || !version.IsPrerelease)); } else if (FloatBehavior == NuGetVersionFloatBehavior.PrereleaseMinor) { // allow the stable version to match return(_minVersion.Major == version.Major && ((version.IsPrerelease && version.Release.StartsWith(_releasePrefix, StringComparison.OrdinalIgnoreCase)) || !version.IsPrerelease)); } else if (FloatBehavior == NuGetVersionFloatBehavior.PrereleaseMajor) { // allow the stable version to match return((version.IsPrerelease && version.Release.StartsWith(_releasePrefix, StringComparison.OrdinalIgnoreCase)) || !version.IsPrerelease); } else if (_floatBehavior == NuGetVersionFloatBehavior.Prerelease) { // allow the stable version to match return(VersionComparer.Version.Equals(_minVersion, version) && ((version.IsPrerelease && version.Release.StartsWith(_releasePrefix, StringComparison.OrdinalIgnoreCase)) || !version.IsPrerelease)); } else if (_floatBehavior == NuGetVersionFloatBehavior.Revision) { return(_minVersion.Major == version.Major && _minVersion.Minor == version.Minor && _minVersion.Patch == version.Patch && !version.IsPrerelease); } else if (_floatBehavior == NuGetVersionFloatBehavior.Patch) { return(_minVersion.Major == version.Major && _minVersion.Minor == version.Minor && !version.IsPrerelease); } else if (_floatBehavior == NuGetVersionFloatBehavior.Minor) { return(_minVersion.Major == version.Major && !version.IsPrerelease); } } return(false); }
/// <summary> /// Parse a floating version into a FloatRange /// </summary> public static bool TryParse(string versionString, out FloatRange range) { range = null; if (versionString != null && !string.IsNullOrWhiteSpace(versionString)) { var firstStarPosition = versionString.IndexOf('*'); var lastStarPosition = versionString.LastIndexOf('*'); string releasePrefix = null; if (versionString.Length == 1 && firstStarPosition == 0) { range = new FloatRange(NuGetVersionFloatBehavior.Major, new NuGetVersion(new Version(0, 0))); } else if (versionString.Equals("*-*")) { range = new FloatRange(NuGetVersionFloatBehavior.AbsoluteLatest, new NuGetVersion("0.0.0-0"), releasePrefix: string.Empty); } else if (firstStarPosition != lastStarPosition && lastStarPosition != -1 && versionString.IndexOf('+') == -1) { var behavior = NuGetVersionFloatBehavior.None; // 2 *s are only allowed in prerelease versions. var dashPosition = versionString.IndexOf('-'); string actualVersion = null; if (dashPosition != -1 && lastStarPosition == versionString.Length - 1 && // Last star is at the end of the full string firstStarPosition == (dashPosition - 1) // First star is right before the first dash. ) { // Get the stable part. var stablePart = versionString.Substring(0, dashPosition - 1); // Get the part without the * stablePart += "0"; var versionParts = CalculateVersionParts(stablePart); switch (versionParts) { case 1: behavior = NuGetVersionFloatBehavior.PrereleaseMajor; break; case 2: behavior = NuGetVersionFloatBehavior.PrereleaseMinor; break; case 3: behavior = NuGetVersionFloatBehavior.PrereleasePatch; break; case 4: behavior = NuGetVersionFloatBehavior.PrereleaseRevision; break; default: break; } var releaseVersion = versionString.Substring(dashPosition + 1); releasePrefix = releaseVersion.Substring(0, releaseVersion.Length - 1); var releasePart = releasePrefix; if (releasePrefix.Length == 0 || releasePrefix.EndsWith(".")) { // 1.0.0-* scenario, an empty label is not a valid version. releasePart += "0"; } actualVersion = stablePart + "-" + releasePart; } if (NuGetVersion.TryParse(actualVersion, out NuGetVersion version)) { range = new FloatRange(behavior, version, releasePrefix); } } // A single * can only appear as the last char in the string. // * cannot appear in the metadata section after the + else if (lastStarPosition == versionString.Length - 1 && versionString.IndexOf('+') == -1) { var behavior = NuGetVersionFloatBehavior.None; var actualVersion = versionString.Substring(0, versionString.Length - 1); if (versionString.IndexOf('-') == -1) { // replace the * with a 0 actualVersion += "0"; var versionParts = CalculateVersionParts(actualVersion); if (versionParts == 2) { behavior = NuGetVersionFloatBehavior.Minor; } else if (versionParts == 3) { behavior = NuGetVersionFloatBehavior.Patch; } else if (versionParts == 4) { behavior = NuGetVersionFloatBehavior.Revision; } } else { behavior = NuGetVersionFloatBehavior.Prerelease; // check for a prefix if (versionString.IndexOf('-') == versionString.LastIndexOf('-')) { releasePrefix = actualVersion.Substring(versionString.LastIndexOf('-') + 1); // For numeric labels 0 is the lowest. For alpha-numeric - is the lowest. if (releasePrefix.Length == 0 || actualVersion.EndsWith(".")) { // 1.0.0-* scenario, an empty label is not a valid version. actualVersion += "0"; } else if (actualVersion.EndsWith("-")) { // Append a dash to allow floating on the next character. actualVersion += "-"; } } } NuGetVersion version = null; if (NuGetVersion.TryParse(actualVersion, out version)) { range = new FloatRange(behavior, version, releasePrefix); } } else { // normal version parse NuGetVersion version = null; if (NuGetVersion.TryParse(versionString, out version)) { // there is no float range for this version range = new FloatRange(NuGetVersionFloatBehavior.None, version); } } } return(range != null); }
/// <summary> /// Parses a VersionRange from its string representation. /// </summary> public static bool TryParse(string value, bool allowFloating, out VersionRange versionRange) { if (value == null) { throw new ArgumentNullException(nameof(value)); } versionRange = null; var trimmedValue = value.Trim(); var charArray = trimmedValue.ToCharArray(); // * is the only range below 3 chars if (allowFloating && charArray.Length == 1 && charArray[0] == '*') { versionRange = new VersionRange(null, true, null, true, new FloatRange(NuGetVersionFloatBehavior.Major), originalString: value); return(true); } // Fail early if the string is too short to be valid if (charArray.Length < 3) { return(false); } string minVersionString = null; string maxVersionString = null; var isMinInclusive = false; var isMaxInclusive = false; NuGetVersion minVersion = null; NuGetVersion maxVersion = null; FloatRange floatRange = null; if (charArray[0] == '(' || charArray[0] == '[') { // The first character must be [ to ( switch (charArray[0]) { case '[': isMinInclusive = true; break; case '(': isMinInclusive = false; break; default: return(false); } // The last character must be ] ot ) switch (charArray[charArray.Length - 1]) { case ']': isMaxInclusive = true; break; case ')': isMaxInclusive = false; break; default: return(false); } // Get rid of the two brackets trimmedValue = trimmedValue.Substring(1, trimmedValue.Length - 2); // Split by comma, and make sure we don't get more than two pieces var parts = trimmedValue.Split(','); if (parts.Length > 2) { return(false); } else { var allEmpty = true; for (int i = 0; i < parts.Length; i++) { if (!string.IsNullOrEmpty(parts[i])) { allEmpty = false; break; } } // If all parts are empty, then neither of upper or lower bounds were specified. Version spec is of the format (,] if (allEmpty) { return(false); } } // If there is only one piece, we use it for both min and max minVersionString = parts[0]; maxVersionString = (parts.Length == 2) ? parts[1] : parts[0]; } else { // default to min inclusive when there are no braces isMinInclusive = true; // use the entire value as the version minVersionString = trimmedValue; } if (!String.IsNullOrWhiteSpace(minVersionString)) { // parse the min version string if (allowFloating && minVersionString.Contains("*")) { // single floating version if (FloatRange.TryParse(minVersionString, out floatRange) && floatRange.HasMinVersion) { minVersion = floatRange.MinVersion; } else { // invalid float return(false); } } else { // single non-floating version if (!NuGetVersion.TryParse(minVersionString, out minVersion)) { // invalid version return(false); } } } // parse the max version string, the max cannot float if (!String.IsNullOrWhiteSpace(maxVersionString)) { if (!NuGetVersion.TryParse(maxVersionString, out maxVersion)) { // invalid version return(false); } } // Successful parse! versionRange = new VersionRange( minVersion: minVersion, includeMinVersion: isMinInclusive, maxVersion: maxVersion, includeMaxVersion: isMaxInclusive, floatRange: floatRange, originalString: value); return(true); }