diff --git a/sls-versions/src/main/java/com/palantir/sls/versions/SlsVersionMatcher.java b/sls-versions/src/main/java/com/palantir/sls/versions/SlsVersionMatcher.java index 78641a37..8fb69b68 100644 --- a/sls-versions/src/main/java/com/palantir/sls/versions/SlsVersionMatcher.java +++ b/sls-versions/src/main/java/com/palantir/sls/versions/SlsVersionMatcher.java @@ -24,6 +24,7 @@ import com.palantir.immutables.style.ImmutablesStyle; import com.palantir.logsafe.SafeArg; import com.palantir.logsafe.UnsafeArg; +import java.util.Comparator; import java.util.Optional; import java.util.OptionalInt; import java.util.regex.Matcher; @@ -43,6 +44,14 @@ public abstract class SlsVersionMatcher { private static final Logger log = LoggerFactory.getLogger(SlsVersionMatcher.class); private static final Pattern PATTERN = Pattern.compile("^(([0-9]+|x))\\.(([0-9]+|x))\\.(([0-9]+|x))$"); + private static final Comparator EMPTY_IS_GREATER = + Comparator.comparingInt(num -> num.isPresent() ? num.getAsInt() : Integer.MAX_VALUE); + + public static final Comparator MATCHER_COMPARATOR = Comparator + .comparing(SlsVersionMatcher::getMajorVersionNumber, EMPTY_IS_GREATER) + .thenComparing(SlsVersionMatcher::getMinorVersionNumber, EMPTY_IS_GREATER) + .thenComparing(SlsVersionMatcher::getPatchVersionNumber, EMPTY_IS_GREATER); + @Value.Auxiliary public abstract String getValue(); public abstract OptionalInt getMajorVersionNumber(); diff --git a/sls-versions/src/test/java/com/palantir/sls/versions/SlsVersionMatcherTest.java b/sls-versions/src/test/java/com/palantir/sls/versions/SlsVersionMatcherTest.java index 9a85ba0e..ac6bcafb 100644 --- a/sls-versions/src/test/java/com/palantir/sls/versions/SlsVersionMatcherTest.java +++ b/sls-versions/src/test/java/com/palantir/sls/versions/SlsVersionMatcherTest.java @@ -109,6 +109,23 @@ public void testCompare() { assertThat(matcher("1.2.x").compare(version("1.2.3-rc1"))).isZero(); } + @Test + public void testMatcherComparator_xTrumpsNumber() { + assertMatcherOrder(SlsVersionMatcher.valueOf("2.6.x"), SlsVersionMatcher.valueOf("2.x.x")); + assertMatcherOrder(SlsVersionMatcher.valueOf("2.6.5"), SlsVersionMatcher.valueOf("2.6.x")); + } + + @Test + public void testMatcherComparator_comparesNumbers() { + assertMatcherOrder(SlsVersionMatcher.valueOf("2.6.x"), SlsVersionMatcher.valueOf("2.7.x")); + assertMatcherOrder(SlsVersionMatcher.valueOf("2.6.5"), SlsVersionMatcher.valueOf("2.6.6")); + } + + private static void assertMatcherOrder(SlsVersionMatcher smaller, SlsVersionMatcher larger) { + assertThat(SlsVersionMatcher.MATCHER_COMPARATOR.compare(smaller, larger)).isLessThan(0); + assertThat(SlsVersionMatcher.MATCHER_COMPARATOR.compare(larger, smaller)).isGreaterThan(0); + } + private static SlsVersionMatcher matcher(String value) { return SlsVersionMatcher.valueOf(value); }