public int compareTo(MavenVersionNumber other) { return compareTo(other, true); }
/** * Compare both versions. * * @param other * Version to be compared to * @param Flag * which indicates whether the snapshot flag should be compared as well. * * @return 0, if same versions. Greater 0 if other is older. Otherwise -1 */ public int compareTo(MavenVersionNumber other, boolean checkSnapshot) { if (other == null) { return 1; } int diff = major - other.major; if (diff == 0) { diff = minor - other.minor; } if (diff == 0) { diff = patch - other.patch; } if (diff == 0 && checkSnapshot) { diff = getSnapshotValue() - other.getSnapshotValue(); } return diff; }
@Test public void testCompareVersions() { MavenVersionNumber a = parse("1.0.0"); assertEquals("Should be 0 since same version", 0, a.compareTo(parse("1.0.0"))); assertEquals("Should be 0 since same version", 1, a.compareTo(parse("0.9.9"))); assertEquals("Should be -1 since newer version", -1, a.compareTo(parse("1.0.1"))); assertEquals("Should be 1 since older(snapshot version)", 1, a.compareTo(parse("1.0.0-SNAPSHOT"))); assertEquals("Should be -1 since newer version", -1, a.compareTo(parse("1.0.1-SNAPSHOT"))); a = parse("1.0.0-SNAPSHOT"); assertEquals("Should be 0 since same version", 0, a.compareTo(parse("1.0.0-SNAPSHOT"))); assertEquals("Should be -1 since newer version", -1, a.compareTo(parse("1.0.1"))); assertEquals("Should be -1 since newer version.", -1, a.compareTo(parse("1.0.0"))); MavenVersionNumber b = parse("1.0.0-RC1-SNAPSHOT"); assertEquals("RC1", b.getPostfix()); assertTrue(b.isSnapshot()); assertEquals("Should be the same", 0, b.compareTo(parse("1.0.0-RC1-SNAPSHOT"))); assertEquals("Should be the same", -1, b.compareTo(parse("1.0.0"))); assertEquals("Should be the same", -1, b.compareTo(parse("1.0.0-RC1"))); } }
/** * Parse the given version number string into a version number object * * @param versionNumberString * version number string * @return version number object or null if not parseable */ public static MavenVersionNumber parse(String versionNumberString) { if (versionNumberString == null) { return null; } Matcher m = snapshotVersion.matcher(versionNumberString); if (!m.matches()) { return null; } MavenVersionNumber versionNumber = new MavenVersionNumber(); versionNumber.fullVersion = versionNumberString; versionNumber.major = Integer.parseInt(m.group(1)); versionNumber.minor = Integer.parseInt(m.group(2)); versionNumber.patch = Integer.parseInt(m.group(3)); String postfix = m.group(4); if (postfix != null) { postfix = postfix.replaceAll("-SNAPSHOT", ""); versionNumber.postfix = postfix; } versionNumber.isSnapshot = versionNumberString.endsWith("-SNAPSHOT"); return versionNumber; }