/// <summary> /// Compare this version with parameter /// </summary> /// <param name="semver">Semver to compare with</param> /// <returns>-1 if less than, 0 if equals, 1 if greater</returns> public int CompareTo(SemVer semver) { if (this.Major < semver.Major) { return -1; } if (this.Major > semver.Major) { return 1; } if (this.Minor < semver.Minor) { return -1; } if (this.Minor > semver.Minor) { return 1; } if (this.Patch < semver.Patch) { return -1; } if (this.Patch > semver.Patch) { return 1; } if (this.PreRelease != null && semver.PreRelease == null) { return -1; } if (this.PreRelease == null && semver.PreRelease != null) { return 1; } if (this.Build != null && semver.Build == null) { return 1; } if (this.Build == null && semver.Build != null) { return -1; } // TODO - handle precedence if both have prerelease or build return 0; }
/// <summary> /// Parse a semver campatable version string and create SemVer /// </summary> /// <param name="version">version string</param> /// <param name="semver">created class</param> /// <returns>0 if success, negative if parse error</returns> private static int ParseHelper(string version, out SemVer semver) { int major = 0; int minor = 0; int patch = 0; semver = null; if (version == null) { return -1; } char[] seps1 = new char[1] { '.' }; string[] parts = version.Split(seps1, 3); if (!int.TryParse(parts[0], out major)) { return -3; } if (parts.Length > 1) { if (!int.TryParse(parts[1], out minor)) { return -4; } } if (parts.Length > 2) { char[] seps2 = new char[2] { '+', '-' }; string[] patchparts = parts[2].Split(seps2, 2); if (!int.TryParse(patchparts[0], out patch)) { return -5; } if (patchparts.Length == 2) { bool isBuild = false; string ext = null; if (parts[2].IndexOf('+') != -1) { isBuild = true; ext = patchparts[1]; } else { isBuild = false; ext = patchparts[1]; } semver = new SemVer(major, minor, patch, isBuild, ext); } else { semver = new SemVer(major, minor, patch); } } else { semver = new SemVer(major, minor, patch); } return 0; }
/// <summary> /// Try to parse a semver campatable version string and create SemVer /// </summary> /// <param name="version">version string</param> /// <param name="semver">created class</param> /// <returns>true if success, false if fails</returns> public static bool TryParse(string version, out SemVer semver) { int rc = ParseHelper(version, out semver); if (rc == 0) { return true; } else { return false; } }