|
1 | 1 | package me.devnatan.inventoryframework.runtime.thirdparty; |
2 | 2 |
|
3 | 3 | import java.util.Objects; |
| 4 | +import java.util.regex.Matcher; |
| 5 | +import java.util.regex.Pattern; |
4 | 6 | import org.bukkit.Bukkit; |
5 | 7 |
|
6 | 8 | public class McVersion implements Comparable<McVersion> { |
7 | 9 |
|
| 10 | + private static final Pattern LEADING_VERSION = |
| 11 | + Pattern.compile("(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?"); |
| 12 | + |
8 | 13 | private static final McVersion CURRENT_VERSION; |
9 | 14 |
|
10 | 15 | static { |
11 | | - final int currentMajor = Integer.parseInt(Bukkit.getBukkitVersion().split("\\.")[0]); |
12 | | - final int currentMinor = |
13 | | - Integer.parseInt(Bukkit.getBukkitVersion().split("\\.")[1].split("-")[0]); |
14 | | - boolean hasPatch = countColons(Bukkit.getBukkitVersion()) == 3; |
15 | | - final int currentPatch = hasPatch |
16 | | - ? Integer.parseInt(Bukkit.getBukkitVersion().split("\\.")[2].split("-")[0]) |
17 | | - : 0; |
18 | | - |
19 | | - CURRENT_VERSION = new McVersion(currentMajor, currentMinor, currentPatch); |
20 | | - } |
21 | | - |
22 | | - private static int countColons(final String string) { |
23 | | - int count = 0; |
24 | | - char[] arr = string.toCharArray(); |
25 | | - for (int i = 0; i < string.length(); i++) { |
26 | | - if (arr[i] == '.') { |
27 | | - count++; |
28 | | - } |
| 16 | + CURRENT_VERSION = parse(Bukkit.getBukkitVersion()); |
| 17 | + } |
| 18 | + |
| 19 | + /** |
| 20 | + * Reads only the leading run of dot-separated numeric segments (major[.minor[.patch]]), |
| 21 | + * so a build/commit suffix appended by a non-standard server fork (e.g. "26.2.build.17406-6bc38be") |
| 22 | + * is ignored instead of throwing a {@link NumberFormatException} out of a static initializer. |
| 23 | + */ |
| 24 | + private static McVersion parse(final String version) { |
| 25 | + final Matcher matcher = LEADING_VERSION.matcher(version); |
| 26 | + if (!matcher.lookingAt()) { |
| 27 | + return new McVersion(1, 0, 0); |
29 | 28 | } |
30 | | - return count; |
| 29 | + |
| 30 | + final int major = Integer.parseInt(matcher.group(1)); |
| 31 | + final int minor = matcher.group(2) != null ? Integer.parseInt(matcher.group(2)) : 0; |
| 32 | + final int patch = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0; |
| 33 | + return new McVersion(major, minor, patch); |
31 | 34 | } |
32 | 35 |
|
33 | 36 | private final int major; |
|
0 commit comments