|
| 1 | +package com.conveyal.r5.util; |
| 2 | + |
| 3 | +import java.util.regex.Matcher; |
| 4 | +import java.util.regex.Pattern; |
| 5 | + |
| 6 | +public class SemVer implements Comparable<SemVer> { |
| 7 | + public final int major; |
| 8 | + public final int minor; |
| 9 | + public final int patch; |
| 10 | + public final String qualifier; // Extra info after the dash, if any |
| 11 | + |
| 12 | + // Regular expression breakdown: |
| 13 | + // ^v : must start with "v" |
| 14 | + // (\\d+) : major version (one or more digits) |
| 15 | + // \\. (\\d+) : minor version (one or more digits), preceded by a dot |
| 16 | + // (?:\\.(\\d+))? : optional patch version, preceded by a dot |
| 17 | + // (?:-(.+))? : optional qualifier after a dash (e.g., "-147-gbb4ecbc") |
| 18 | + // $ : end of string |
| 19 | + private static final Pattern pattern = Pattern.compile("^v(\\d+)\\.(\\d+)(?:\\.(\\d+))?(?:-(.+))?$"); |
| 20 | + |
| 21 | + // Constructor that parses version strings |
| 22 | + public SemVer(String version) { |
| 23 | + if (version == null) { |
| 24 | + throw new IllegalArgumentException("Version string cannot be null"); |
| 25 | + } |
| 26 | + |
| 27 | + Matcher matcher = pattern.matcher(version); |
| 28 | + if (!matcher.matches()) { |
| 29 | + throw new IllegalArgumentException("Invalid version string: " + version); |
| 30 | + } |
| 31 | + this.major = Integer.parseInt(matcher.group(1)); |
| 32 | + this.minor = Integer.parseInt(matcher.group(2)); |
| 33 | + this.patch = matcher.group(3) == null ? 0 : Integer.parseInt(matcher.group(3)); |
| 34 | + this.qualifier = matcher.group(4) == null ? "" : matcher.group(4); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Compares this version to another based on major, minor, and patch numbers. |
| 39 | + * If these are equal, then a version without a qualifier is considered higher than one with a qualifier. |
| 40 | + */ |
| 41 | + @Override |
| 42 | + public int compareTo(SemVer other) { |
| 43 | + if (this.major != other.major) return Integer.compare(this.major, other.major); |
| 44 | + if (this.minor != other.minor) return Integer.compare(this.minor, other.minor); |
| 45 | + if (this.patch != other.patch) return Integer.compare(this.patch, other.patch); |
| 46 | + |
| 47 | + // Compare qualifiers lexicographically. |
| 48 | + return this.qualifier.compareTo(other.qualifier); |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Compare if version "a" is greater than or equal to version "b". |
| 53 | + * |
| 54 | + * @param a SemVer parseable string |
| 55 | + * @param b Semver parseable string |
| 56 | + * @return true if a >= b |
| 57 | + */ |
| 58 | + public static boolean gte(String a, String b) { |
| 59 | + return new SemVer(a).compareTo(new SemVer(b)) >= 0; |
| 60 | + } |
| 61 | +} |
0 commit comments