Models simple version strings. Does not attempt to be semver compatible, and gleefully fails to handle non-numerical values, except accidentally. This is sufficient for handling the version strings we care about from Docker.
| 25 | * strings we care about from Docker. |
| 26 | */ |
| 27 | class Version { |
| 28 | |
| 29 | private final String versionString; |
| 30 | private final String[] segments; |
| 31 | |
| 32 | public Version(String versionString) { |
| 33 | this.versionString = Require.nonNull("Version string", versionString); |
| 34 | |
| 35 | this.segments = versionString.split("\\."); |
| 36 | } |
| 37 | |
| 38 | public boolean equalTo(Version other) { |
| 39 | int max = Math.max(segments.length, other.segments.length); |
| 40 | |
| 41 | for (int i = 0; i < max; i++) { |
| 42 | if (compare(segments, other.segments, i) != 0) { |
| 43 | return false; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | return true; |
| 48 | } |
| 49 | |
| 50 | public boolean isLessThan(Version other) { |
| 51 | int max = Math.max(segments.length, other.segments.length); |
| 52 | |
| 53 | for (int i = 0; i < max; i++) { |
| 54 | if (compare(segments, other.segments, i) > 0) { |
| 55 | return false; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | return !equalTo(other); |
| 60 | } |
| 61 | |
| 62 | public boolean isGreaterThan(Version other) { |
| 63 | int max = Math.max(segments.length, other.segments.length); |
| 64 | |
| 65 | for (int i = 0; i < max; i++) { |
| 66 | if (compare(segments, other.segments, i) < 0) { |
| 67 | return false; |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | return !equalTo(other); |
| 72 | } |
| 73 | |
| 74 | public String toString() { |
| 75 | return versionString; |
| 76 | } |
| 77 | |
| 78 | // Returns a negative integer, zero, or a positive integer as the first |
| 79 | // argument is less than, equal to, or greater than the second. We attempt |
| 80 | // numerical comparisons first, and then a lexical comparison |
| 81 | private int compare(String[] ours, String[] theirs, int index) { |
| 82 | try { |
| 83 | long mine = index < ours.length ? Long.parseLong(ours[index]) : 0L; |
| 84 | long others = index < theirs.length ? Long.parseLong(theirs[index]) : 0L; |