-
-
Save prashant4224/a088095a0e594bf304b5f115ac225a9d to your computer and use it in GitHub Desktop.
Simple SemVer version parsing and comparison in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Version implements Comparable<Version> { | |
@NonNull | |
public final int[] numbers; | |
public Version(@NonNull String version) { | |
final String split[] = version.split("\\-")[0].split("\\."); | |
numbers = new int[split.length]; | |
for (int i = 0; i < split.length; i++) { | |
numbers[i] = Integer.valueOf(split[i]); | |
} | |
} | |
@Override | |
public int compareTo(@NonNull Version another) { | |
final int maxLength = Math.max(numbers.length, another.numbers.length); | |
for (int i = 0; i < maxLength; i++) { | |
final int left = i < numbers.length ? numbers[i] : 0; | |
final int right = i < another.numbers.length ? another.numbers[i] : 0; | |
if (left != right) { | |
return left < right ? -1 : 1; | |
} | |
} | |
return 0; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class VersionTest { | |
@Test | |
public void newInstance_withTwoDotRelease_isParsedCorrectly() { | |
final Version version = new Version("1.26.6"); | |
assertThat(version.numbers, is(new int[]{1, 26, 6})); | |
} | |
@Test | |
public void newInstance_withTwoDotReleaseAndPreReleaseName_isParsedCorrectly() { | |
final Version version = new Version("1.26.6-DEBUG"); | |
assertThat(version.numbers, is(new int[]{1, 26, 6})); | |
} | |
@Test | |
public void compareTo_withEarlierVersion_isGreaterThan() { | |
assertThat(new Version("2.0.0").compareTo(new Version("1.0.0")), is(1)); | |
} | |
@Test | |
public void compareTo_withSameVersion_isEqual() { | |
assertThat(new Version("2.0.0").compareTo(new Version("2.0.0")), is(0)); | |
} | |
@Test | |
public void compareTo_withLaterVersion_isLessThan() { | |
assertThat(new Version("1.0.0").compareTo(new Version("2.0.0")), is(-1)); | |
} | |
@Test | |
public void compareTo_withMorePreciseSameVersion_isFalse() { | |
assertThat(new Version("1").compareTo(new Version("1.0.0")), is(0)); | |
} | |
@Test | |
public void compareTo_withMorePreciseEarlierVersion_isFalse() { | |
assertThat(new Version("2").compareTo(new Version("1.0.0")), is(1)); | |
} | |
@Test | |
public void compareTo_withMorePreciseLaterVersion_isLessThan() { | |
assertThat(new Version("1").compareTo(new Version("1.0.1")), is(-1)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment