Skip to content

Commit

Permalink
Add a SlsVersionMatcher comparator (#3)
Browse files Browse the repository at this point in the history
* Add a SlsVersionMatcher comparator

* More tests
  • Loading branch information
dansanduleac authored and iamdanfox committed Jun 18, 2018
1 parent fef350d commit 77d0655
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<OptionalInt> EMPTY_IS_GREATER =
Comparator.comparingInt(num -> num.isPresent() ? num.getAsInt() : Integer.MAX_VALUE);

public static final Comparator<SlsVersionMatcher> 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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down

0 comments on commit 77d0655

Please sign in to comment.