using System;
using System.Text.RegularExpressions;
namespace StardewModdingAPI.Toolkit
{
/// A semantic version with an optional release tag.
/// The implementation is defined by Semantic Version 2.0 (http://semver.org/).
public class SemanticVersion : ISemanticVersion
{
/*********
** Properties
*********/
/// A regex pattern matching a version within a larger string.
internal const string UnboundedVersionPattern = @"(?>(?0|[1-9]\d*))\.(?>(?0|[1-9]\d*))(?>(?:\.(?0|[1-9]\d*))?)(?:-(?(?>[a-z0-9]+[\-\.]?)+))?";
/// A regular expression matching a semantic version string.
///
/// This pattern is derived from the BNF documentation in the semver repo,
/// with three important deviations intended to support Stardew Valley mod conventions:
/// - allows short-form "x.y" versions;
/// - allows hyphens in prerelease tags as synonyms for dots (like "-unofficial-update.3");
/// - doesn't allow '+build' suffixes.
///
internal static readonly Regex Regex = new Regex($@"^{SemanticVersion.UnboundedVersionPattern}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.ExplicitCapture);
/*********
** Accessors
*********/
/// The major version incremented for major API changes.
public int Major { get; }
/// The minor version incremented for backwards-compatible changes.
public int Minor { get; }
/// The patch version for backwards-compatible bug fixes.
public int Patch { get; }
/// An optional prerelease tag.
public string Tag { get; }
/*********
** Public methods
*********/
/// Construct an instance.
/// The major version incremented for major API changes.
/// The minor version incremented for backwards-compatible changes.
/// The patch version for backwards-compatible fixes.
/// An optional prerelease tag.
public SemanticVersion(int major, int minor, int patch, string tag = null)
{
this.Major = major;
this.Minor = minor;
this.Patch = patch;
this.Tag = this.GetNormalisedTag(tag);
}
/// Construct an instance.
/// The assembly version.
/// The is null.
public SemanticVersion(Version version)
{
if (version == null)
throw new ArgumentNullException(nameof(version), "The input version can't be null.");
this.Major = version.Major;
this.Minor = version.Minor;
this.Patch = version.Build;
}
/// Construct an instance.
/// The semantic version string.
/// The is null.
/// The is not a valid semantic version.
public SemanticVersion(string version)
{
// parse
if (version == null)
throw new ArgumentNullException(nameof(version), "The input version string can't be null.");
var match = SemanticVersion.Regex.Match(version.Trim());
if (!match.Success)
throw new FormatException($"The input '{version}' isn't a valid semantic version.");
// initialise
this.Major = int.Parse(match.Groups["major"].Value);
this.Minor = match.Groups["minor"].Success ? int.Parse(match.Groups["minor"].Value) : 0;
this.Patch = match.Groups["patch"].Success ? int.Parse(match.Groups["patch"].Value) : 0;
this.Tag = match.Groups["prerelease"].Success ? this.GetNormalisedTag(match.Groups["prerelease"].Value) : null;
}
/// Get an integer indicating whether this version precedes (less than 0), supercedes (more than 0), or is equivalent to (0) the specified version.
/// The version to compare with this instance.
/// The value is null.
public int CompareTo(ISemanticVersion other)
{
if (other == null)
throw new ArgumentNullException(nameof(other));
return this.CompareTo(other.Major, other.Minor, other.Patch, other.Tag);
}
/// Indicates whether the current object is equal to another object of the same type.
/// true if the current object is equal to the parameter; otherwise, false.
/// An object to compare with this object.
public bool Equals(ISemanticVersion other)
{
return other != null && this.CompareTo(other) == 0;
}
/// Whether this is a pre-release version.
public bool IsPrerelease()
{
return !string.IsNullOrWhiteSpace(this.Tag);
}
/// Get whether this version is older than the specified version.
/// The version to compare with this instance.
public bool IsOlderThan(ISemanticVersion other)
{
return this.CompareTo(other) < 0;
}
/// Get whether this version is newer than the specified version.
/// The version to compare with this instance.
public bool IsNewerThan(ISemanticVersion other)
{
return this.CompareTo(other) > 0;
}
/// Get whether this version is between two specified versions (inclusively).
/// The minimum version.
/// The maximum version.
public bool IsBetween(ISemanticVersion min, ISemanticVersion max)
{
return this.CompareTo(min) >= 0 && this.CompareTo(max) <= 0;
}
/// Get a string representation of the version.
public override string ToString()
{
// version
string result = this.Patch != 0
? $"{this.Major}.{this.Minor}.{this.Patch}"
: $"{this.Major}.{this.Minor}";
// tag
string tag = this.Tag;
if (tag != null)
result += $"-{tag}";
return result;
}
/// Parse a version string without throwing an exception if it fails.
/// The version string.
/// The parsed representation.
/// Returns whether parsing the version succeeded.
public static bool TryParse(string version, out ISemanticVersion parsed)
{
try
{
parsed = new SemanticVersion(version);
return true;
}
catch
{
parsed = null;
return false;
}
}
/*********
** Private methods
*********/
/// Get a normalised build tag.
/// The tag to normalise.
private string GetNormalisedTag(string tag)
{
tag = tag?.Trim();
return !string.IsNullOrWhiteSpace(tag) ? tag : null;
}
/// Get an integer indicating whether this version precedes (less than 0), supercedes (more than 0), or is equivalent to (0) the specified version.
/// The major version to compare with this instance.
/// The minor version to compare with this instance.
/// The patch version to compare with this instance.
/// The prerelease tag to compare with this instance.
private int CompareTo(int otherMajor, int otherMinor, int otherPatch, string otherTag)
{
const int same = 0;
const int curNewer = 1;
const int curOlder = -1;
// compare stable versions
if (this.Major != otherMajor)
return this.Major.CompareTo(otherMajor);
if (this.Minor != otherMinor)
return this.Minor.CompareTo(otherMinor);
if (this.Patch != otherPatch)
return this.Patch.CompareTo(otherPatch);
if (this.Tag == otherTag)
return same;
// stable supercedes pre-release
bool curIsStable = string.IsNullOrWhiteSpace(this.Tag);
bool otherIsStable = string.IsNullOrWhiteSpace(otherTag);
if (curIsStable)
return curNewer;
if (otherIsStable)
return curOlder;
// compare two pre-release tag values
string[] curParts = this.Tag.Split('.', '-');
string[] otherParts = otherTag.Split('.', '-');
for (int i = 0; i < curParts.Length; i++)
{
// longer prerelease tag supercedes if otherwise equal
if (otherParts.Length <= i)
return curNewer;
// compare if different
if (curParts[i] != otherParts[i])
{
// compare numerically if possible
{
if (int.TryParse(curParts[i], out int curNum) && int.TryParse(otherParts[i], out int otherNum))
return curNum.CompareTo(otherNum);
}
// else compare lexically
return string.Compare(curParts[i], otherParts[i], StringComparison.OrdinalIgnoreCase);
}
}
// fallback (this should never happen)
return string.Compare(this.ToString(), new SemanticVersion(otherMajor, otherMinor, otherPatch, otherTag).ToString(), StringComparison.InvariantCultureIgnoreCase);
}
}
}